diff --git a/CoreAgent.API/Controllers/BaseApiController.cs b/CoreAgent.API/Controllers/BaseApiController.cs new file mode 100644 index 0000000..d520a51 --- /dev/null +++ b/CoreAgent.API/Controllers/BaseApiController.cs @@ -0,0 +1,80 @@ +using CoreAgent.Domain.Models; +using MediatR; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using System.Net; + +namespace CoreAgent.API.Controllers +{ + [ApiController] + [Route("api/v{version:apiVersion}/[controller]")] + public abstract class BaseApiController : ControllerBase + { + protected readonly IMediator _mediator; + protected readonly ILogger _logger; + + protected BaseApiController(IMediator mediator, ILogger logger) + { + _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + protected async Task HandleRequest(TRequest request) + where TRequest : IRequest + { + try + { + _logger.LogInformation("Handling request of type {RequestType}", typeof(TRequest).Name); + var response = await _mediator.Send(request); + return new ApiActionResult(ApiResponse.CreateSuccess(response)); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error handling request of type {RequestType}", typeof(TRequest).Name); + return new ApiActionResult( + ApiResponse.CreateError(ex.Message), + HttpStatusCode.InternalServerError + ); + } + } + + protected async Task HandleRequest(TRequest request) + where TRequest : IRequest + { + try + { + _logger.LogInformation("Handling request of type {RequestType}", typeof(TRequest).Name); + await _mediator.Send(request); + return new ApiActionResult(ApiResponse.CreateSuccess()); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error handling request of type {RequestType}", typeof(TRequest).Name); + return new ApiActionResult( + ApiResponse.CreateError(ex.Message), + HttpStatusCode.InternalServerError + ); + } + } + + protected IActionResult Success(T data, string message = null) + { + return new ApiActionResult(ApiResponse.CreateSuccess(data, message)); + } + + protected IActionResult Success(string message = null) + { + return new ApiActionResult(ApiResponse.CreateSuccess(message)); + } + + protected IActionResult Error(string message, List errors = null, HttpStatusCode statusCode = HttpStatusCode.BadRequest) + { + return new ApiActionResult(ApiResponse.CreateError(message, errors), statusCode); + } + + protected IActionResult Error(string message, List errors = null, HttpStatusCode statusCode = HttpStatusCode.BadRequest) + { + return new ApiActionResult(ApiResponse.CreateError(message, errors), statusCode); + } + } +} \ No newline at end of file diff --git a/CoreAgent.API/Controllers/CellularNetworkController.cs b/CoreAgent.API/Controllers/CellularNetworkController.cs new file mode 100644 index 0000000..d7a577c --- /dev/null +++ b/CoreAgent.API/Controllers/CellularNetworkController.cs @@ -0,0 +1,48 @@ +using CoreAgent.Application.Commands.CellularNetwork; +using MediatR; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; + +namespace CoreAgent.API.Controllers; + +/// +/// 蜂窝网络控制器 +/// +[ApiController] +[ApiVersion("1.0")] +[Route("api/v{version:apiVersion}/[controller]")] +public class CellularNetworkController : BaseApiController +{ + private readonly ILogger _logger; + + public CellularNetworkController( + IMediator mediator, + ILogger logger) : base(mediator, logger) + { + _logger = logger; + } + + /// + /// 启动蜂窝网络 + /// + /// 启动命令 + /// 操作结果 + [HttpPost("start")] + public async Task Start([FromBody] StartCellularNetworkCommand command) + { + _logger.LogInformation("收到启动蜂窝网络请求: {InterfaceName}", command.InterfaceName); + return await HandleRequest(command); + } + + /// + /// 停止蜂窝网络 + /// + /// 停止命令 + /// 操作结果 + [HttpPost("stop")] + public async Task Stop([FromBody] StopCellularNetworkCommand command) + { + _logger.LogInformation("收到停止蜂窝网络请求: {InterfaceName}", command.InterfaceName); + return await HandleRequest(command); + } +} \ No newline at end of file diff --git a/CoreAgent.API/CoreAgent.API.csproj b/CoreAgent.API/CoreAgent.API.csproj index 7809c42..74a2e13 100644 --- a/CoreAgent.API/CoreAgent.API.csproj +++ b/CoreAgent.API/CoreAgent.API.csproj @@ -11,11 +11,13 @@ + + diff --git a/CoreAgent.API/Startup.cs b/CoreAgent.API/Startup.cs index e41eee5..6d71de7 100644 --- a/CoreAgent.API/Startup.cs +++ b/CoreAgent.API/Startup.cs @@ -1,9 +1,6 @@ + using CoreAgent.Infrastructure.Extensions; -using CoreAgent.Infrastructure.Logging; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; +using System.Reflection; using Serilog; namespace CoreAgent.API @@ -21,10 +18,17 @@ namespace CoreAgent.API public void ConfigureServices(IServiceCollection services) { + // Add MediatR + services.AddMediatR(cfg => { + cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()); + cfg.RegisterServicesFromAssembly(typeof(Startup).Assembly); + cfg.RegisterServicesFromAssembly(Assembly.Load("CoreAgent.Application")); + }); // 添加基础设施服务 services.AddInfrastructure(Configuration); + // 添加控制器 services.AddControllers(); @@ -87,6 +91,7 @@ namespace CoreAgent.API .AddApiVersioningExtension(config) .AddRequestLogging(config) .AddAuthorization() + .AddCommandCustomService() .AddSwaggerGen(); } diff --git a/CoreAgent.API/logs/log-20250611.txt b/CoreAgent.API/logs/log-20250611.txt new file mode 100644 index 0000000..b4d0da3 --- /dev/null +++ b/CoreAgent.API/logs/log-20250611.txt @@ -0,0 +1,308 @@ +2025-06-11 00:02:46.491 +08:00 [INF] Logger initialized successfully +2025-06-11 00:02:46.529 +08:00 [INF] Application starting... +2025-06-11 00:02:47.971 +08:00 [FTL] Application failed to start: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: CoreAgent.Domain.Interfaces.ICommandStrategyFactory Lifetime: Singleton ImplementationType: CoreAgent.Infrastructure.Command.CommandStrategyFactory': Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'CoreAgent.Infrastructure.Command.CommandStrategyFactory'.) +System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: CoreAgent.Domain.Interfaces.ICommandStrategyFactory Lifetime: Singleton ImplementationType: CoreAgent.Infrastructure.Command.CommandStrategyFactory': Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'CoreAgent.Infrastructure.Command.CommandStrategyFactory'.) + ---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: CoreAgent.Domain.Interfaces.ICommandStrategyFactory Lifetime: Singleton ImplementationType: CoreAgent.Infrastructure.Command.CommandStrategyFactory': Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'CoreAgent.Infrastructure.Command.CommandStrategyFactory'. + ---> System.InvalidOperationException: Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'CoreAgent.Infrastructure.Command.CommandStrategyFactory'. + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, Int32 slot) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options) + at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options) + at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build() + at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build() + at Program.
$(String[] args) in D:\HistoryCode\CoreAgent\src\CoreAgent.API\Program.cs:line 20 +2025-06-11 00:02:48.108 +08:00 [FTL] Startup failure details: {"Message":"Some services are not able to be constructed (Error while validating the service descriptor \u0027ServiceType: CoreAgent.Domain.Interfaces.ICommandStrategyFactory Lifetime: Singleton ImplementationType: CoreAgent.Infrastructure.Command.CommandStrategyFactory\u0027: Unable to resolve service for type \u0027Serilog.ILogger\u0027 while attempting to activate \u0027CoreAgent.Infrastructure.Command.CommandStrategyFactory\u0027.)","StackTrace":" at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection\u00601 serviceDescriptors, ServiceProviderOptions options)\r\n at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)\r\n at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build()\r\n at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()\r\n at Program.\u003CMain\u003E$(String[] args) in D:\\HistoryCode\\CoreAgent\\src\\CoreAgent.API\\Program.cs:line 20","Source":"Microsoft.Extensions.DependencyInjection","InnerException":"Error while validating the service descriptor \u0027ServiceType: CoreAgent.Domain.Interfaces.ICommandStrategyFactory Lifetime: Singleton ImplementationType: CoreAgent.Infrastructure.Command.CommandStrategyFactory\u0027: Unable to resolve service for type \u0027Serilog.ILogger\u0027 while attempting to activate \u0027CoreAgent.Infrastructure.Command.CommandStrategyFactory\u0027."} +2025-06-11 00:03:56.281 +08:00 [INF] Logger initialized successfully +2025-06-11 00:03:56.316 +08:00 [INF] Application starting... +2025-06-11 00:03:56.362 +08:00 [FTL] Application failed to start: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: CoreAgent.Domain.Interfaces.ICommandStrategyFactory Lifetime: Singleton ImplementationType: CoreAgent.Infrastructure.Command.CommandStrategyFactory': Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'CoreAgent.Infrastructure.Command.CommandStrategyFactory'.) +System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: CoreAgent.Domain.Interfaces.ICommandStrategyFactory Lifetime: Singleton ImplementationType: CoreAgent.Infrastructure.Command.CommandStrategyFactory': Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'CoreAgent.Infrastructure.Command.CommandStrategyFactory'.) + ---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: CoreAgent.Domain.Interfaces.ICommandStrategyFactory Lifetime: Singleton ImplementationType: CoreAgent.Infrastructure.Command.CommandStrategyFactory': Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'CoreAgent.Infrastructure.Command.CommandStrategyFactory'. + ---> System.InvalidOperationException: Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'CoreAgent.Infrastructure.Command.CommandStrategyFactory'. + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, Int32 slot) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options) + at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options) + at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build() + at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build() + at Program.
$(String[] args) in D:\HistoryCode\CoreAgent\src\CoreAgent.API\Program.cs:line 20 +2025-06-11 00:03:56.424 +08:00 [FTL] Startup failure details: {"Message":"Some services are not able to be constructed (Error while validating the service descriptor \u0027ServiceType: CoreAgent.Domain.Interfaces.ICommandStrategyFactory Lifetime: Singleton ImplementationType: CoreAgent.Infrastructure.Command.CommandStrategyFactory\u0027: Unable to resolve service for type \u0027Serilog.ILogger\u0027 while attempting to activate \u0027CoreAgent.Infrastructure.Command.CommandStrategyFactory\u0027.)","StackTrace":" at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection\u00601 serviceDescriptors, ServiceProviderOptions options)\r\n at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)\r\n at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build()\r\n at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()\r\n at Program.\u003CMain\u003E$(String[] args) in D:\\HistoryCode\\CoreAgent\\src\\CoreAgent.API\\Program.cs:line 20","Source":"Microsoft.Extensions.DependencyInjection","InnerException":"Error while validating the service descriptor \u0027ServiceType: CoreAgent.Domain.Interfaces.ICommandStrategyFactory Lifetime: Singleton ImplementationType: CoreAgent.Infrastructure.Command.CommandStrategyFactory\u0027: Unable to resolve service for type \u0027Serilog.ILogger\u0027 while attempting to activate \u0027CoreAgent.Infrastructure.Command.CommandStrategyFactory\u0027."} +2025-06-11 00:05:46.844 +08:00 [INF] Logger initialized successfully +2025-06-11 00:05:46.881 +08:00 [INF] Application starting... +2025-06-11 00:05:46.923 +08:00 [FTL] Application failed to start: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: CoreAgent.Domain.Interfaces.ICommandStrategyFactory Lifetime: Singleton ImplementationType: CoreAgent.Infrastructure.Command.CommandStrategyFactory': Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'CoreAgent.Infrastructure.Command.CommandStrategyFactory'.) +System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: CoreAgent.Domain.Interfaces.ICommandStrategyFactory Lifetime: Singleton ImplementationType: CoreAgent.Infrastructure.Command.CommandStrategyFactory': Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'CoreAgent.Infrastructure.Command.CommandStrategyFactory'.) + ---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: CoreAgent.Domain.Interfaces.ICommandStrategyFactory Lifetime: Singleton ImplementationType: CoreAgent.Infrastructure.Command.CommandStrategyFactory': Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'CoreAgent.Infrastructure.Command.CommandStrategyFactory'. + ---> System.InvalidOperationException: Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'CoreAgent.Infrastructure.Command.CommandStrategyFactory'. + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, Int32 slot) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options) + at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options) + at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build() + at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build() + at Program.
$(String[] args) in D:\HistoryCode\CoreAgent\src\CoreAgent.API\Program.cs:line 20 +2025-06-11 00:05:46.967 +08:00 [FTL] Startup failure details: {"Message":"Some services are not able to be constructed (Error while validating the service descriptor \u0027ServiceType: CoreAgent.Domain.Interfaces.ICommandStrategyFactory Lifetime: Singleton ImplementationType: CoreAgent.Infrastructure.Command.CommandStrategyFactory\u0027: Unable to resolve service for type \u0027Serilog.ILogger\u0027 while attempting to activate \u0027CoreAgent.Infrastructure.Command.CommandStrategyFactory\u0027.)","StackTrace":" at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection\u00601 serviceDescriptors, ServiceProviderOptions options)\r\n at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)\r\n at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build()\r\n at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()\r\n at Program.\u003CMain\u003E$(String[] args) in D:\\HistoryCode\\CoreAgent\\src\\CoreAgent.API\\Program.cs:line 20","Source":"Microsoft.Extensions.DependencyInjection","InnerException":"Error while validating the service descriptor \u0027ServiceType: CoreAgent.Domain.Interfaces.ICommandStrategyFactory Lifetime: Singleton ImplementationType: CoreAgent.Infrastructure.Command.CommandStrategyFactory\u0027: Unable to resolve service for type \u0027Serilog.ILogger\u0027 while attempting to activate \u0027CoreAgent.Infrastructure.Command.CommandStrategyFactory\u0027."} +2025-06-11 00:06:35.367 +08:00 [INF] Logger initialized successfully +2025-06-11 00:06:35.401 +08:00 [INF] Application starting... +2025-06-11 00:06:35.925 +08:00 [INF] Application startup completed +2025-06-11 00:18:39.803 +08:00 [INF] Logger initialized successfully +2025-06-11 00:18:39.853 +08:00 [INF] Application starting... +2025-06-11 00:18:42.251 +08:00 [INF] Application startup completed +2025-06-11 00:18:56.881 +08:00 [INF] Logger initialized successfully +2025-06-11 00:18:56.926 +08:00 [INF] Application starting... +2025-06-11 00:18:57.374 +08:00 [INF] Application startup completed +2025-06-11 00:19:06.139 +08:00 [INF] Request started: GET /api/v1/WeatherForecast +2025-06-11 00:19:06.199 +08:00 [INF] Weather forecast requested +2025-06-11 00:19:06.227 +08:00 [INF] Response for GET /api/v1/WeatherForecast: 200 - [{"date":"2025-06-12","temperatureC":39,"summary":"Cool","temperatureF":102},{"date":"2025-06-13","temperatureC":16,"summary":"Cool","temperatureF":60},{"date":"2025-06-14","temperatureC":4,"summary":"Balmy","temperatureF":39},{"date":"2025-06-15","temperatureC":11,"summary":"Freezing","temperatureF":51},{"date":"2025-06-16","temperatureC":-1,"summary":"Chilly","temperatureF":31}] +2025-06-11 00:19:06.245 +08:00 [INF] Request completed: GET /api/v1/WeatherForecast in 111ms with status code 200 +2025-06-11 00:28:28.605 +08:00 [INF] Logger initialized successfully +2025-06-11 00:28:28.640 +08:00 [INF] Application starting... +2025-06-11 00:28:28.892 +08:00 [INF] Application startup completed +2025-06-11 00:28:29.786 +08:00 [INF] Application is stopping... +2025-06-11 00:28:29.800 +08:00 [INF] Application has stopped. +2025-06-11 00:28:44.067 +08:00 [INF] Logger initialized successfully +2025-06-11 00:28:44.118 +08:00 [INF] Application starting... +2025-06-11 00:28:44.579 +08:00 [INF] Application startup completed +2025-06-11 00:53:27.958 +08:00 [INF] Logger initialized successfully +2025-06-11 00:53:28.002 +08:00 [INF] Application starting... +2025-06-11 00:53:30.633 +08:00 [INF] Application startup completed +2025-06-11 00:53:37.999 +08:00 [INF] Request started: POST /api/v1/CellularNetwork/start +2025-06-11 00:53:38.120 +08:00 [INF] 收到启动蜂窝网络请求: string +2025-06-11 00:53:38.128 +08:00 [INF] Handling request of type StartCellularNetworkCommand +2025-06-11 00:53:38.225 +08:00 [ERR] Error handling request of type StartCellularNetworkCommand +System.InvalidOperationException: No service for type 'MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean]' has been registered. + at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) + at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) + at MediatR.Wrappers.RequestHandlerWrapperImpl`2.<>c__DisplayClass1_0.g__Handler|0() + at MediatR.Wrappers.RequestHandlerWrapperImpl`2.Handle(IRequest`1 request, IServiceProvider serviceProvider, CancellationToken cancellationToken) + at MediatR.Mediator.Send[TResponse](IRequest`1 request, CancellationToken cancellationToken) + at CoreAgent.API.Controllers.BaseApiController.HandleRequest[TRequest,TResponse](TRequest request) in D:\HistoryCode\CoreAgent\src\CoreAgent.API\Controllers\BaseApiController.cs:line 28 +2025-06-11 00:53:38.299 +08:00 [INF] Response for POST /api/v1/CellularNetwork/start: 500 - {"success":false,"message":"No service for type 'MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean]' has been registered.","data":false,"errors":[]} +2025-06-11 00:53:38.323 +08:00 [INF] Request completed: POST /api/v1/CellularNetwork/start in 329ms with status code 500 +2025-06-11 00:55:18.744 +08:00 [INF] Logger initialized successfully +2025-06-11 00:55:18.784 +08:00 [INF] Application starting... +2025-06-11 00:55:20.433 +08:00 [FTL] Application failed to start: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'.) +System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'.) + ---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'. + ---> System.InvalidOperationException: Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'. + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, Int32 slot) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options) + at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options) + at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build() + at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build() + at Program.
$(String[] args) in D:\HistoryCode\CoreAgent\src\CoreAgent.API\Program.cs:line 20 + ---> (Inner Exception #1) System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'. + ---> System.InvalidOperationException: Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'. + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, Int32 slot) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)<--- + + ---> (Inner Exception #2) System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'. + ---> System.InvalidOperationException: Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'. + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, Int32 slot) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)<--- + +2025-06-11 00:55:20.556 +08:00 [FTL] Startup failure details: {"Message":"Some services are not able to be constructed (Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027.) (Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler\u0027.) (Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler\u0027.)","StackTrace":" at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection\u00601 serviceDescriptors, ServiceProviderOptions options)\r\n at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)\r\n at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build()\r\n at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()\r\n at Program.\u003CMain\u003E$(String[] args) in D:\\HistoryCode\\CoreAgent\\src\\CoreAgent.API\\Program.cs:line 20","Source":"Microsoft.Extensions.DependencyInjection","InnerException":"Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027."} +2025-06-11 00:55:57.494 +08:00 [INF] Logger initialized successfully +2025-06-11 00:55:57.538 +08:00 [INF] Application starting... +2025-06-11 00:55:59.958 +08:00 [INF] Application startup completed +2025-06-11 00:56:06.299 +08:00 [INF] Request started: POST /api/v1/CellularNetwork/start +2025-06-11 00:56:06.419 +08:00 [INF] 收到启动蜂窝网络请求: string +2025-06-11 00:56:06.426 +08:00 [INF] Handling request of type StartCellularNetworkCommand +2025-06-11 00:56:06.507 +08:00 [ERR] Error handling request of type StartCellularNetworkCommand +System.InvalidOperationException: No service for type 'MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean]' has been registered. + at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) + at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) + at MediatR.Wrappers.RequestHandlerWrapperImpl`2.<>c__DisplayClass1_0.g__Handler|0() + at MediatR.Wrappers.RequestHandlerWrapperImpl`2.Handle(IRequest`1 request, IServiceProvider serviceProvider, CancellationToken cancellationToken) + at MediatR.Mediator.Send[TResponse](IRequest`1 request, CancellationToken cancellationToken) + at CoreAgent.API.Controllers.BaseApiController.HandleRequest[TRequest,TResponse](TRequest request) in D:\HistoryCode\CoreAgent\src\CoreAgent.API\Controllers\BaseApiController.cs:line 28 +2025-06-11 00:56:06.555 +08:00 [INF] Response for POST /api/v1/CellularNetwork/start: 500 - {"success":false,"message":"No service for type 'MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean]' has been registered.","data":false,"errors":[]} +2025-06-11 00:56:06.573 +08:00 [INF] Request completed: POST /api/v1/CellularNetwork/start in 281ms with status code 500 +2025-06-11 00:57:56.184 +08:00 [INF] Logger initialized successfully +2025-06-11 00:57:56.241 +08:00 [INF] Application starting... +2025-06-11 00:57:58.051 +08:00 [FTL] Application failed to start: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'.) +System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'.) + ---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'. + ---> System.InvalidOperationException: Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'. + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, Int32 slot) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options) + at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options) + at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build() + at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build() + at Program.
$(String[] args) in D:\HistoryCode\CoreAgent\src\CoreAgent.API\Program.cs:line 20 + ---> (Inner Exception #1) System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'. + ---> System.InvalidOperationException: Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'. + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, Int32 slot) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)<--- + + ---> (Inner Exception #2) System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'. + ---> System.InvalidOperationException: Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'. + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, Int32 slot) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)<--- + +2025-06-11 00:57:58.199 +08:00 [FTL] Startup failure details: {"Message":"Some services are not able to be constructed (Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027.) (Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler\u0027.) (Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler\u0027.)","StackTrace":" at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection\u00601 serviceDescriptors, ServiceProviderOptions options)\r\n at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)\r\n at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build()\r\n at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()\r\n at Program.\u003CMain\u003E$(String[] args) in D:\\HistoryCode\\CoreAgent\\src\\CoreAgent.API\\Program.cs:line 20","Source":"Microsoft.Extensions.DependencyInjection","InnerException":"Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027."} +2025-06-11 00:59:14.196 +08:00 [INF] Logger initialized successfully +2025-06-11 00:59:14.238 +08:00 [INF] Application starting... +2025-06-11 00:59:14.293 +08:00 [FTL] Application failed to start: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'.) +System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'.) + ---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'. + ---> System.InvalidOperationException: Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'. + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, Int32 slot) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options) + at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options) + at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build() + at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build() + at Program.
$(String[] args) in D:\HistoryCode\CoreAgent\src\CoreAgent.API\Program.cs:line 20 + ---> (Inner Exception #1) System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'. + ---> System.InvalidOperationException: Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'. + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, Int32 slot) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)<--- + + ---> (Inner Exception #2) System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'. + ---> System.InvalidOperationException: Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'. + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, Int32 slot) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)<--- + +2025-06-11 00:59:14.363 +08:00 [FTL] Startup failure details: {"Message":"Some services are not able to be constructed (Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027.) (Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler\u0027.) (Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler\u0027.)","StackTrace":" at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection\u00601 serviceDescriptors, ServiceProviderOptions options)\r\n at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)\r\n at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build()\r\n at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()\r\n at Program.\u003CMain\u003E$(String[] args) in D:\\HistoryCode\\CoreAgent\\src\\CoreAgent.API\\Program.cs:line 20","Source":"Microsoft.Extensions.DependencyInjection","InnerException":"Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027."} +2025-06-11 01:00:05.938 +08:00 [INF] Logger initialized successfully +2025-06-11 01:00:05.995 +08:00 [INF] Application starting... +2025-06-11 01:00:07.598 +08:00 [FTL] Application failed to start: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'.) +System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'.) (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'.) + ---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'. + ---> System.InvalidOperationException: Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler'. + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, Int32 slot) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options) + at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options) + at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build() + at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build() + at Program.
$(String[] args) in D:\HistoryCode\CoreAgent\src\CoreAgent.API\Program.cs:line 20 + ---> (Inner Exception #1) System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'. + ---> System.InvalidOperationException: Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler'. + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, Int32 slot) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)<--- + + ---> (Inner Exception #2) System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler': Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'. + ---> System.InvalidOperationException: Unable to resolve service for type 'CoreAgent.Domain.Interfaces.ICellularNetworkService' while attempting to activate 'CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler'. + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, ServiceIdentifier serviceIdentifier, Type implementationType, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, Int32 slot) + at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + --- End of inner exception stack trace --- + at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor) + at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)<--- + +2025-06-11 01:00:07.709 +08:00 [FTL] Startup failure details: {"Message":"Some services are not able to be constructed (Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027.) (Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.StartCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.StartCellularNetworkCommandHandler\u0027.) (Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.StopCellularNetworkCommand,System.Boolean] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.StopCellularNetworkCommandHandler\u0027.)","StackTrace":" at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection\u00601 serviceDescriptors, ServiceProviderOptions options)\r\n at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)\r\n at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build()\r\n at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()\r\n at Program.\u003CMain\u003E$(String[] args) in D:\\HistoryCode\\CoreAgent\\src\\CoreAgent.API\\Program.cs:line 20","Source":"Microsoft.Extensions.DependencyInjection","InnerException":"Error while validating the service descriptor \u0027ServiceType: MediatR.IRequestHandler\u00602[CoreAgent.Application.Commands.CellularNetwork.GetCellularNetworkStatusCommand,CoreAgent.Application.Commands.CellularNetwork.CellularNetworkStatus] Lifetime: Transient ImplementationType: CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027: Unable to resolve service for type \u0027CoreAgent.Domain.Interfaces.ICellularNetworkService\u0027 while attempting to activate \u0027CoreAgent.Application.Handlers.CellularNetwork.GetCellularNetworkStatusCommandHandler\u0027."} +2025-06-11 01:00:38.549 +08:00 [INF] Logger initialized successfully +2025-06-11 01:00:38.593 +08:00 [INF] Application starting... +2025-06-11 01:00:39.229 +08:00 [INF] Application startup completed +2025-06-11 01:00:55.414 +08:00 [INF] Application is stopping... +2025-06-11 01:00:55.429 +08:00 [INF] Application has stopped. +2025-06-11 01:01:08.260 +08:00 [INF] Logger initialized successfully +2025-06-11 01:01:08.310 +08:00 [INF] Application starting... +2025-06-11 01:01:08.769 +08:00 [INF] Application startup completed +2025-06-11 01:01:13.658 +08:00 [INF] Request started: POST /api/v1/CellularNetwork/start +2025-06-11 01:01:13.801 +08:00 [INF] 收到启动蜂窝网络请求: string +2025-06-11 01:01:13.807 +08:00 [INF] Handling request of type StartCellularNetworkCommand +2025-06-11 01:01:13.820 +08:00 [INF] 正在启动蜂窝网络接口: string +2025-06-11 01:01:13.827 +08:00 [INF] 正在启动蜂窝网络接口: string +2025-06-11 01:01:15.013 +08:00 [ERR] 启动蜂窝网络接口失败: string +System.Exception: 命令执行失败: + at CoreAgent.Infrastructure.Services.CellularNetworkService.ExecuteCommandAsync(String command) in D:\HistoryCode\CoreAgent\src\CoreAgent.Infrastructure\Services\CellularNetworkService.cs:line 117 + at CoreAgent.Infrastructure.Services.CellularNetworkService.StartAsync(String interfaceName, CellularNetworkConfig config) in D:\HistoryCode\CoreAgent\src\CoreAgent.Infrastructure\Services\CellularNetworkService.cs:line 28 +2025-06-11 01:01:15.049 +08:00 [WRN] 蜂窝网络接口 string 启动失败 +2025-06-11 01:01:15.073 +08:00 [INF] Response for POST /api/v1/CellularNetwork/start: 200 - {"success":true,"message":null,"data":false,"errors":[]} +2025-06-11 01:01:15.088 +08:00 [INF] Request completed: POST /api/v1/CellularNetwork/start in 1436ms with status code 200 diff --git a/CoreAgent.Application/Commands/CellularNetwork/GetCellularNetworkStatusCommand.cs b/CoreAgent.Application/Commands/CellularNetwork/GetCellularNetworkStatusCommand.cs new file mode 100644 index 0000000..919ad76 --- /dev/null +++ b/CoreAgent.Application/Commands/CellularNetwork/GetCellularNetworkStatusCommand.cs @@ -0,0 +1,41 @@ +using CoreAgent.Domain.Models; +using MediatR; + +namespace CoreAgent.Application.Commands.CellularNetwork; + +/// +/// 获取蜂窝网络状态命令 +/// +public class GetCellularNetworkStatusCommand : IRequest +{ + /// + /// 网络接口名称 + /// + public string InterfaceName { get; set; } +} + +/// +/// 蜂窝网络状态 +/// +public class CellularNetworkStatus +{ + /// + /// 是否启用 + /// + public bool IsEnabled { get; set; } + + /// + /// 连接状态 + /// + public string ConnectionState { get; set; } + + /// + /// 信号强度 + /// + public int SignalStrength { get; set; } + + /// + /// 运营商名称 + /// + public string CarrierName { get; set; } +} \ No newline at end of file diff --git a/CoreAgent.Application/Commands/CellularNetwork/StartCellularNetworkCommand.cs b/CoreAgent.Application/Commands/CellularNetwork/StartCellularNetworkCommand.cs new file mode 100644 index 0000000..5c20bfc --- /dev/null +++ b/CoreAgent.Application/Commands/CellularNetwork/StartCellularNetworkCommand.cs @@ -0,0 +1,20 @@ +using CoreAgent.Domain.Models; +using MediatR; + +namespace CoreAgent.Application.Commands.CellularNetwork; + +/// +/// 启动蜂窝网络命令 +/// +public class StartCellularNetworkCommand : IRequest +{ + /// + /// 网络接口名称 + /// + public string InterfaceName { get; set; } + + /// + /// 网络配置 + /// + public CellularNetworkConfig Config { get; set; } +} \ No newline at end of file diff --git a/CoreAgent.Application/Commands/CellularNetwork/StartCellularNetworkCommandHandler.cs b/CoreAgent.Application/Commands/CellularNetwork/StartCellularNetworkCommandHandler.cs new file mode 100644 index 0000000..1552b18 --- /dev/null +++ b/CoreAgent.Application/Commands/CellularNetwork/StartCellularNetworkCommandHandler.cs @@ -0,0 +1,33 @@ +using CoreAgent.Domain.Interfaces; +using MediatR; +using Microsoft.Extensions.Logging; + +namespace CoreAgent.Application.Commands.CellularNetwork; + +public class StartCellularNetworkCommandHandler : IRequestHandler +{ + private readonly ICellularNetworkService _cellularNetworkService; + private readonly ILogger _logger; + + public StartCellularNetworkCommandHandler( + ICellularNetworkService cellularNetworkService, + ILogger logger) + { + _cellularNetworkService = cellularNetworkService; + _logger = logger; + } + + public async Task Handle(StartCellularNetworkCommand request, CancellationToken cancellationToken) + { + try + { + _logger.LogInformation("Starting cellular network for interface: {InterfaceName}", request.InterfaceName); + return await _cellularNetworkService.StartAsync(request.InterfaceName, request.Config); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error starting cellular network for interface: {InterfaceName}", request.InterfaceName); + throw; + } + } +} \ No newline at end of file diff --git a/CoreAgent.Application/Commands/CellularNetwork/StopCellularNetworkCommand.cs b/CoreAgent.Application/Commands/CellularNetwork/StopCellularNetworkCommand.cs new file mode 100644 index 0000000..da9f884 --- /dev/null +++ b/CoreAgent.Application/Commands/CellularNetwork/StopCellularNetworkCommand.cs @@ -0,0 +1,14 @@ +using MediatR; + +namespace CoreAgent.Application.Commands.CellularNetwork; + +/// +/// 停止蜂窝网络命令 +/// +public class StopCellularNetworkCommand : IRequest +{ + /// + /// 网络接口名称 + /// + public string InterfaceName { get; set; } +} \ No newline at end of file diff --git a/CoreAgent.Application/CoreAgent.Application.csproj b/CoreAgent.Application/CoreAgent.Application.csproj index fa71b7a..24eff6c 100644 --- a/CoreAgent.Application/CoreAgent.Application.csproj +++ b/CoreAgent.Application/CoreAgent.Application.csproj @@ -6,4 +6,13 @@ enable + + + + + + + + + diff --git a/CoreAgent.Application/Handlers/CellularNetwork/GetCellularNetworkStatusCommandHandler.cs b/CoreAgent.Application/Handlers/CellularNetwork/GetCellularNetworkStatusCommandHandler.cs new file mode 100644 index 0000000..c6cc216 --- /dev/null +++ b/CoreAgent.Application/Handlers/CellularNetwork/GetCellularNetworkStatusCommandHandler.cs @@ -0,0 +1,48 @@ +using CoreAgent.Application.Commands.CellularNetwork; +using CoreAgent.Domain.Interfaces; +using MediatR; +using Microsoft.Extensions.Logging; + +namespace CoreAgent.Application.Handlers.CellularNetwork; + +/// +/// 获取蜂窝网络状态命令处理器 +/// +public class GetCellularNetworkStatusCommandHandler : IRequestHandler +{ + private readonly ICellularNetworkService _cellularNetworkService; + private readonly ILogger _logger; + + public GetCellularNetworkStatusCommandHandler( + ICellularNetworkService cellularNetworkService, + ILogger logger) + { + _cellularNetworkService = cellularNetworkService; + _logger = logger; + } + + public async Task Handle(GetCellularNetworkStatusCommand request, CancellationToken cancellationToken) + { + try + { + _logger.LogInformation("正在获取蜂窝网络状态: {InterfaceName}", request.InterfaceName); + + // 这里需要扩展ICellularNetworkService接口,添加获取状态的方法 + // var status = await _cellularNetworkService.GetStatusAsync(request.InterfaceName); + + // 临时返回模拟数据 + return new CellularNetworkStatus + { + IsEnabled = true, + ConnectionState = "Connected", + SignalStrength = 80, + CarrierName = "China Mobile" + }; + } + catch (Exception ex) + { + _logger.LogError(ex, "获取蜂窝网络状态失败: {InterfaceName}", request.InterfaceName); + throw; + } + } +} \ No newline at end of file diff --git a/CoreAgent.Application/Handlers/CellularNetwork/StartCellularNetworkCommandHandler.cs b/CoreAgent.Application/Handlers/CellularNetwork/StartCellularNetworkCommandHandler.cs new file mode 100644 index 0000000..f178a94 --- /dev/null +++ b/CoreAgent.Application/Handlers/CellularNetwork/StartCellularNetworkCommandHandler.cs @@ -0,0 +1,48 @@ +using CoreAgent.Application.Commands.CellularNetwork; +using CoreAgent.Domain.Interfaces; +using MediatR; +using Microsoft.Extensions.Logging; + +namespace CoreAgent.Application.Handlers.CellularNetwork; + +/// +/// 启动蜂窝网络命令处理器 +/// +public class StartCellularNetworkCommandHandler : IRequestHandler +{ + private readonly ICellularNetworkService _cellularNetworkService; + private readonly ILogger _logger; + + public StartCellularNetworkCommandHandler( + ICellularNetworkService cellularNetworkService, + ILogger logger) + { + _cellularNetworkService = cellularNetworkService; + _logger = logger; + } + + public async Task Handle(StartCellularNetworkCommand request, CancellationToken cancellationToken) + { + try + { + _logger.LogInformation("正在启动蜂窝网络接口: {InterfaceName}", request.InterfaceName); + var result = await _cellularNetworkService.StartAsync(request.InterfaceName, request.Config); + + if (result) + { + _logger.LogInformation("蜂窝网络接口 {InterfaceName} 启动成功", request.InterfaceName); + } + else + { + _logger.LogWarning("蜂窝网络接口 {InterfaceName} 启动失败", request.InterfaceName); + } + + return result; + } + catch (Exception ex) + { + _logger.LogError(ex, "启动蜂窝网络接口 {InterfaceName} 失败", request.InterfaceName); + return false; + } + } +} \ No newline at end of file diff --git a/CoreAgent.Application/Handlers/CellularNetwork/StopCellularNetworkCommandHandler.cs b/CoreAgent.Application/Handlers/CellularNetwork/StopCellularNetworkCommandHandler.cs new file mode 100644 index 0000000..c6d2a17 --- /dev/null +++ b/CoreAgent.Application/Handlers/CellularNetwork/StopCellularNetworkCommandHandler.cs @@ -0,0 +1,48 @@ +using CoreAgent.Application.Commands.CellularNetwork; +using CoreAgent.Domain.Interfaces; +using MediatR; +using Microsoft.Extensions.Logging; + +namespace CoreAgent.Application.Handlers.CellularNetwork; + +/// +/// 停止蜂窝网络命令处理器 +/// +public class StopCellularNetworkCommandHandler : IRequestHandler +{ + private readonly ICellularNetworkService _cellularNetworkService; + private readonly ILogger _logger; + + public StopCellularNetworkCommandHandler( + ICellularNetworkService cellularNetworkService, + ILogger logger) + { + _cellularNetworkService = cellularNetworkService; + _logger = logger; + } + + public async Task Handle(StopCellularNetworkCommand request, CancellationToken cancellationToken) + { + try + { + _logger.LogInformation("正在停止蜂窝网络接口: {InterfaceName}", request.InterfaceName); + var result = await _cellularNetworkService.StopAsync(request.InterfaceName); + + if (result) + { + _logger.LogInformation("蜂窝网络接口 {InterfaceName} 停止成功", request.InterfaceName); + } + else + { + _logger.LogWarning("蜂窝网络接口 {InterfaceName} 停止失败", request.InterfaceName); + } + + return result; + } + catch (Exception ex) + { + _logger.LogError(ex, "停止蜂窝网络接口 {InterfaceName} 失败", request.InterfaceName); + return false; + } + } +} \ No newline at end of file diff --git a/CoreAgent.Domain/CoreAgent.Domain.csproj b/CoreAgent.Domain/CoreAgent.Domain.csproj index 812f847..358f371 100644 --- a/CoreAgent.Domain/CoreAgent.Domain.csproj +++ b/CoreAgent.Domain/CoreAgent.Domain.csproj @@ -7,6 +7,7 @@ + diff --git a/CoreAgent.Domain/Interfaces/ICellularNetworkService.cs b/CoreAgent.Domain/Interfaces/ICellularNetworkService.cs new file mode 100644 index 0000000..dd27669 --- /dev/null +++ b/CoreAgent.Domain/Interfaces/ICellularNetworkService.cs @@ -0,0 +1,31 @@ +using CoreAgent.Domain.Models; + +namespace CoreAgent.Domain.Interfaces; + +/// +/// 蜂窝网络服务接口 +/// +public interface ICellularNetworkService +{ + /// + /// 启动蜂窝网络 + /// + /// 网络接口名称 + /// 网络配置 + /// 操作是否成功 + Task StartAsync(string interfaceName, CellularNetworkConfig config); + + /// + /// 停止蜂窝网络 + /// + /// 网络接口名称 + /// 操作是否成功 + Task StopAsync(string interfaceName); + + /// + /// 获取蜂窝网络状态 + /// + /// 网络接口名称 + /// 网络状态信息 + Task GetStatusAsync(string interfaceName); +} \ No newline at end of file diff --git a/CoreAgent.Domain/Interfaces/ICommandStrategyFactory.cs b/CoreAgent.Domain/Interfaces/ICommandStrategyFactory.cs new file mode 100644 index 0000000..35a859f --- /dev/null +++ b/CoreAgent.Domain/Interfaces/ICommandStrategyFactory.cs @@ -0,0 +1,28 @@ +namespace CoreAgent.Domain.Interfaces; + +/// +/// 命令策略工厂接口 +/// +public interface ICommandStrategyFactory +{ + /// + /// 创建命令策略 + /// + /// 命令策略实例 + ICommandStrategy CreateStrategy(); +} + +/// +/// 命令策略接口 +/// +public interface ICommandStrategy +{ + /// + /// 执行命令并返回缓冲结果 + /// + /// 要执行的命令 + /// 取消令牌源 + /// 日志记录器 + /// 命令执行结果 + Task ExecuteBufferedAsync(string command, CancellationTokenSource source); +} \ No newline at end of file diff --git a/CoreAgent.Domain/Models/ApiActionResult.cs b/CoreAgent.Domain/Models/ApiActionResult.cs new file mode 100644 index 0000000..281f5ec --- /dev/null +++ b/CoreAgent.Domain/Models/ApiActionResult.cs @@ -0,0 +1,49 @@ +using Microsoft.AspNetCore.Mvc; +using System.Net; + +namespace CoreAgent.Domain.Models +{ + public class ApiActionResult : IActionResult + { + private readonly ApiResponse _response; + private readonly HttpStatusCode _statusCode; + + public ApiActionResult(ApiResponse response, HttpStatusCode statusCode = HttpStatusCode.OK) + { + _response = response; + _statusCode = statusCode; + } + + public async Task ExecuteResultAsync(ActionContext context) + { + var objectResult = new ObjectResult(_response) + { + StatusCode = (int)_statusCode + }; + + await objectResult.ExecuteResultAsync(context); + } + } + + public class ApiActionResult : IActionResult + { + private readonly ApiResponse _response; + private readonly HttpStatusCode _statusCode; + + public ApiActionResult(ApiResponse response, HttpStatusCode statusCode = HttpStatusCode.OK) + { + _response = response; + _statusCode = statusCode; + } + + public async Task ExecuteResultAsync(ActionContext context) + { + var objectResult = new ObjectResult(_response) + { + StatusCode = (int)_statusCode + }; + + await objectResult.ExecuteResultAsync(context); + } + } +} \ No newline at end of file diff --git a/CoreAgent.Domain/Models/ApiResponse.cs b/CoreAgent.Domain/Models/ApiResponse.cs new file mode 100644 index 0000000..20a7a09 --- /dev/null +++ b/CoreAgent.Domain/Models/ApiResponse.cs @@ -0,0 +1,58 @@ +namespace CoreAgent.Domain.Models +{ + public class ApiResponse + { + public bool Success { get; set; } + public string? Message { get; set; } + public T? Data { get; set; } + public List Errors { get; set; } + + public ApiResponse() + { + Success = true; + Errors = new List(); + } + + public static ApiResponse CreateSuccess(T data, string? message = null) + { + return new ApiResponse + { + Success = true, + Data = data, + Message = message + }; + } + + public static ApiResponse CreateError(string message, List? errors = null) + { + return new ApiResponse + { + Success = false, + Message = message, + Errors = errors ?? new List() + }; + } + } + + public class ApiResponse : ApiResponse + { + public new static ApiResponse CreateSuccess(string? message = null) + { + return new ApiResponse + { + Success = true, + Message = message + }; + } + + public new static ApiResponse CreateError(string message, List? errors = null) + { + return new ApiResponse + { + Success = false, + Message = message, + Errors = errors ?? new List() + }; + } + } +} \ No newline at end of file diff --git a/CoreAgent.Domain/Models/CellularNetworkConfig.cs b/CoreAgent.Domain/Models/CellularNetworkConfig.cs new file mode 100644 index 0000000..be7c115 --- /dev/null +++ b/CoreAgent.Domain/Models/CellularNetworkConfig.cs @@ -0,0 +1,22 @@ +namespace CoreAgent.Domain.Models; + +/// +/// 蜂窝网络配置 +/// +public class CellularNetworkConfig +{ + /// + /// APN名称 + /// + public string Apn { get; set; } + + /// + /// 用户名 + /// + public string Username { get; set; } + + /// + /// 密码 + /// + public string Password { get; set; } +} \ No newline at end of file diff --git a/CoreAgent.Domain/Models/CellularNetworkStatus.cs b/CoreAgent.Domain/Models/CellularNetworkStatus.cs new file mode 100644 index 0000000..b8c164c --- /dev/null +++ b/CoreAgent.Domain/Models/CellularNetworkStatus.cs @@ -0,0 +1,27 @@ +namespace CoreAgent.Domain.Models; + +/// +/// 蜂窝网络状态 +/// +public class CellularNetworkStatus +{ + /// + /// 是否启用 + /// + public bool IsEnabled { get; set; } + + /// + /// 连接状态 + /// + public string ConnectionState { get; set; } + + /// + /// 信号强度 + /// + public int SignalStrength { get; set; } + + /// + /// 运营商名称 + /// + public string CarrierName { get; set; } +} \ No newline at end of file diff --git a/CoreAgent.Infrastructure/Command/CommandStrategyFactory.cs b/CoreAgent.Infrastructure/Command/CommandStrategyFactory.cs new file mode 100644 index 0000000..8cf36a2 --- /dev/null +++ b/CoreAgent.Infrastructure/Command/CommandStrategyFactory.cs @@ -0,0 +1,44 @@ +using CoreAgent.Domain.Interfaces; +using Microsoft.Extensions.Logging; +using System.Runtime.InteropServices; + +namespace CoreAgent.Infrastructure.Command; + +/// +/// 命令策略工厂实现 +/// +public class CommandStrategyFactory : ICommandStrategyFactory +{ + private readonly ILogger _logger; + private readonly ILoggerFactory _loggerFactory; + + public CommandStrategyFactory(ILogger logger, ILoggerFactory loggerFactory) + { + _logger = logger; + _loggerFactory = loggerFactory; + } + + /// + /// 创建适合当前操作系统的命令策略 + /// + /// 命令策略实例 + /// 当操作系统不是Windows或Linux时抛出 + public ICommandStrategy CreateStrategy() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + _logger.LogInformation("Creating Windows command strategy"); + return new WindowsCommandStrategy(_loggerFactory.CreateLogger()); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + _logger.LogInformation("Creating Linux command strategy"); + return new LinuxCommandStrategy(_loggerFactory.CreateLogger()); + } + else + { + _logger.LogError("Unsupported operating system"); + throw new PlatformNotSupportedException("Only Windows and Linux are supported."); + } + } +} \ No newline at end of file diff --git a/CoreAgent.Infrastructure/Command/LinuxCommandStrategy.cs b/CoreAgent.Infrastructure/Command/LinuxCommandStrategy.cs new file mode 100644 index 0000000..fdd5329 --- /dev/null +++ b/CoreAgent.Infrastructure/Command/LinuxCommandStrategy.cs @@ -0,0 +1,123 @@ +using CliWrap; +using CliWrap.Buffered; +using CoreAgent.Domain.Interfaces; +using Microsoft.Extensions.Logging; + +namespace CoreAgent.Infrastructure.Command; + +/// +/// Linux命令策略实现 +/// +public class LinuxCommandStrategy : ICommandStrategy +{ + private readonly ILogger _logger; + + public LinuxCommandStrategy(ILogger logger) + { + _logger = logger; + } + + public async Task ExecuteBufferedAsync(string arguments, Action onOutputReceived, CancellationTokenSource source) + { + try + { + _logger.LogDebug("start ExecuteAsync cmd :{Arguments}", arguments); + var cmd = Cli.Wrap("/bin/bash") + .WithArguments($"-c \"{arguments}\"") + .WithStandardOutputPipe(PipeTarget.ToDelegate(onOutputReceived)) + .WithStandardErrorPipe(PipeTarget.ToDelegate(onOutputReceived)) + .WithValidation(CommandResultValidation.None); + var result = await cmd.ExecuteBufferedAsync(source.Token); + _logger.LogInformation("{Arguments} result:{IsSuccess}", arguments, result.IsSuccess); + } + catch (Exception ex) + { + _logger.LogError(ex, "ExecuteAsync cmd {Arguments} failed", arguments); + } + } + + public async Task ExecuteBufferedAsync(string arguments, CancellationTokenSource source) + { + try + { + _logger.LogDebug("start ExecuteAsync cmd :{Arguments}", arguments); + var cmd = Cli.Wrap("/bin/bash") + .WithArguments($"-c \"{arguments}\"") + .WithValidation(CommandResultValidation.None); + var cmdResult = await cmd.ExecuteBufferedAsync(source.Token); + string result = string.Empty; + if (cmdResult.IsSuccess) + result = cmdResult.StandardOutput; + else + result = cmdResult.StandardError; + _logger.LogDebug("ExecuteAsync cmd :{Arguments} StandardOutput:{Output} :StandardError {Error}", + arguments, cmdResult.StandardOutput, cmdResult.StandardError); + return result; + } + catch (Exception ex) + { + _logger.LogError(ex, "ExecuteAsync cmd {Arguments} failed", arguments); + return string.Empty; + } + } + + public async Task ExecuteAsync(string arguments, CancellationTokenSource source) + { + try + { + _logger.LogDebug("start ExecuteAsync cmd :{Arguments}", arguments); + var cmd = await Cli.Wrap("/bin/bash") + .WithArguments($"-c \"{arguments}\"") + .ExecuteAsync(source.Token); + _logger.LogDebug("ExecuteAsync cmd :{Arguments} :result {IsSuccess}", arguments, cmd.IsSuccess); + return cmd.IsSuccess; + } + catch (Exception ex) + { + _logger.LogError(ex, "ExecuteAsync cmd {Arguments} failed", arguments); + return false; + } + } + + public async Task ExecuteBufferedAsync(string[] arguments, CancellationTokenSource source, string command = "/root/enb/doc/ws.js") + { + try + { + _logger.LogDebug("start ExecuteAsync cmd :{Arguments}", arguments); + var cmd = Cli.Wrap(command) + .WithArguments(arguments) + .WithValidation(CommandResultValidation.None); + var cmdResult = await cmd.ExecuteBufferedAsync(source.Token); + string result = string.Empty; + if (cmdResult.IsSuccess) + result = cmdResult.StandardOutput; + else + result = cmdResult.StandardError; + _logger.LogDebug("ExecuteAsync cmd :{Arguments} :result {Result}", arguments, result); + return result; + } + catch (Exception ex) + { + _logger.LogError(ex, "ExecuteAsync cmd {Arguments} failed", arguments); + return string.Empty; + } + } + + public async Task ExecuteAsync(string[] arguments, CancellationTokenSource source, string command = "/root/enb/doc/ws.js") + { + try + { + _logger.LogDebug("start ExecuteAsync cmd :{Arguments}", arguments); + var cmd = await Cli.Wrap(command) + .WithArguments(arguments) + .WithValidation(CommandResultValidation.None) + .ExecuteAsync(source.Token); + return cmd.IsSuccess; + } + catch (Exception ex) + { + _logger.LogError(ex, "ExecuteAsync cmd {Arguments} failed", arguments); + return false; + } + } +} \ No newline at end of file diff --git a/CoreAgent.Infrastructure/Command/WindowsCommandStrategy.cs b/CoreAgent.Infrastructure/Command/WindowsCommandStrategy.cs new file mode 100644 index 0000000..b3789bf --- /dev/null +++ b/CoreAgent.Infrastructure/Command/WindowsCommandStrategy.cs @@ -0,0 +1,123 @@ +using CliWrap; +using CliWrap.Buffered; +using CoreAgent.Domain.Interfaces; +using Microsoft.Extensions.Logging; + +namespace CoreAgent.Infrastructure.Command; + +/// +/// Windows命令策略实现 +/// +public class WindowsCommandStrategy : ICommandStrategy +{ + private readonly ILogger _logger; + + public WindowsCommandStrategy(ILogger logger) + { + _logger = logger; + } + + public async Task ExecuteBufferedAsync(string arguments, Action onOutputReceived, CancellationTokenSource source) + { + try + { + _logger.LogDebug("start ExecuteAsync cmd :{Arguments}", arguments); + var cmd = Cli.Wrap("cmd.exe") + .WithArguments($"/c {arguments}") + .WithStandardOutputPipe(PipeTarget.ToDelegate(onOutputReceived)) + .WithStandardErrorPipe(PipeTarget.ToDelegate(onOutputReceived)) + .WithValidation(CommandResultValidation.None); + var result = await cmd.ExecuteBufferedAsync(source.Token); + _logger.LogInformation("{Arguments} result:{IsSuccess}", arguments, result.IsSuccess); + } + catch (Exception ex) + { + _logger.LogError(ex, "ExecuteAsync cmd {Arguments} failed", arguments); + } + } + + public async Task ExecuteBufferedAsync(string arguments, CancellationTokenSource source) + { + try + { + _logger.LogDebug("start ExecuteAsync cmd :{Arguments}", arguments); + var cmd = Cli.Wrap("cmd.exe") + .WithArguments($"/c {arguments}") + .WithValidation(CommandResultValidation.None); + var cmdResult = await cmd.ExecuteBufferedAsync(source.Token); + string result = string.Empty; + if (cmdResult.IsSuccess) + result = cmdResult.StandardOutput; + else + result = cmdResult.StandardError; + _logger.LogDebug("ExecuteAsync cmd :{Arguments} StandardOutput:{Output} :StandardError {Error}", + arguments, cmdResult.StandardOutput, cmdResult.StandardError); + return result; + } + catch (Exception ex) + { + _logger.LogError(ex, "ExecuteAsync cmd {Arguments} failed", arguments); + return string.Empty; + } + } + + public async Task ExecuteAsync(string arguments, CancellationTokenSource source) + { + try + { + _logger.LogDebug("start ExecuteAsync cmd :{Arguments}", arguments); + var cmd = await Cli.Wrap("cmd.exe") + .WithArguments($"/c {arguments}") + .ExecuteAsync(source.Token); + _logger.LogDebug("ExecuteAsync cmd :{Arguments} :result {IsSuccess}", arguments, cmd.IsSuccess); + return cmd.IsSuccess; + } + catch (Exception ex) + { + _logger.LogError(ex, "ExecuteAsync cmd {Arguments} failed", arguments); + return false; + } + } + + public async Task ExecuteBufferedAsync(string[] arguments, CancellationTokenSource source, string command = "powershell.exe") + { + try + { + _logger.LogDebug("start ExecuteAsync cmd :{Arguments}", arguments); + var cmd = Cli.Wrap(command) + .WithArguments(arguments) + .WithValidation(CommandResultValidation.None); + var cmdResult = await cmd.ExecuteBufferedAsync(source.Token); + string result = string.Empty; + if (cmdResult.IsSuccess) + result = cmdResult.StandardOutput; + else + result = cmdResult.StandardError; + _logger.LogDebug("ExecuteAsync cmd :{Arguments} :result {Result}", arguments, result); + return result; + } + catch (Exception ex) + { + _logger.LogError(ex, "ExecuteAsync cmd {Arguments} failed", arguments); + return string.Empty; + } + } + + public async Task ExecuteAsync(string[] arguments, CancellationTokenSource source, string command = "powershell.exe") + { + try + { + _logger.LogDebug("start ExecuteAsync cmd :{Arguments}", arguments); + var cmd = await Cli.Wrap(command) + .WithArguments(arguments) + .WithValidation(CommandResultValidation.None) + .ExecuteAsync(source.Token); + return cmd.IsSuccess; + } + catch (Exception ex) + { + _logger.LogError(ex, "ExecuteAsync cmd {Arguments} failed", arguments); + return false; + } + } +} \ No newline at end of file diff --git a/CoreAgent.Infrastructure/CoreAgent.Infrastructure.csproj b/CoreAgent.Infrastructure/CoreAgent.Infrastructure.csproj index 5090aed..45f6941 100644 --- a/CoreAgent.Infrastructure/CoreAgent.Infrastructure.csproj +++ b/CoreAgent.Infrastructure/CoreAgent.Infrastructure.csproj @@ -7,6 +7,7 @@ + diff --git a/CoreAgent.Infrastructure/Extensions/ServiceCollectionExtensions.cs b/CoreAgent.Infrastructure/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..27b6771 --- /dev/null +++ b/CoreAgent.Infrastructure/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,27 @@ +using CoreAgent.Domain.Interfaces; +using CoreAgent.Infrastructure.Command; +using CoreAgent.Infrastructure.Services; +using Microsoft.Extensions.DependencyInjection; + +namespace CoreAgent.Infrastructure.Extensions; + +/// +/// 服务集合扩展方法 +/// +public static class ServiceCollectionExtensions +{ + /// + /// 添加命令策略服务 + /// + /// 服务集合 + /// 服务集合 + public static IServiceCollection AddCommandCustomService(this IServiceCollection services) + { + // 注册命令策略工厂 + services.AddSingleton(); + + // 注册 ICellularNetworkService + services.AddScoped(); + return services; + } +} \ No newline at end of file diff --git a/CoreAgent.Infrastructure/Network/IPAddressUtils.cs b/CoreAgent.Infrastructure/Network/IPAddressUtils.cs new file mode 100644 index 0000000..cb0b2d4 --- /dev/null +++ b/CoreAgent.Infrastructure/Network/IPAddressUtils.cs @@ -0,0 +1,168 @@ +using System.Numerics; +using CoreAgent.Domain.Interfaces; + +namespace CoreAgent.Infrastructure.Network; + +/// +/// 提供IP地址相关的工具方法 +/// +public static class IPAddressUtils +{ + /// + /// 检查两个IPv4地址是否在同一个子网内 + /// + /// 第一个IP地址 + /// 第二个IP地址 + /// 子网掩码 + /// 如果两个IP地址在同一个子网内返回true,否则返回false + /// 当IP地址或子网掩码不是IPv4格式时抛出 + public static bool IsSameIPv4Subnet(System.Net.IPAddress ip1, System.Net.IPAddress ip2, System.Net.IPAddress subnetMask) + { + if (ip1.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork || + ip2.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork || + subnetMask.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) + { + throw new ArgumentException("IP addresses and subnet mask must be IPv4."); + } + + byte[] ip1Bytes = ip1.GetAddressBytes(); + byte[] ip2Bytes = ip2.GetAddressBytes(); + byte[] subnetBytes = subnetMask.GetAddressBytes(); + + byte[] network1 = new byte[4]; + byte[] network2 = new byte[4]; + + for (int i = 0; i < 4; i++) + { + network1[i] = (byte)(ip1Bytes[i] & subnetBytes[i]); + network2[i] = (byte)(ip2Bytes[i] & subnetBytes[i]); + } + + return new System.Net.IPAddress(network1).Equals(new System.Net.IPAddress(network2)); + } + + /// + /// 检查两个IPv6地址是否在同一个子网内 + /// + /// 第一个IP地址 + /// 第二个IP地址 + /// 前缀长度 + /// 如果两个IP地址在同一个子网内返回true,否则返回false + /// 当IP地址不是IPv6格式时抛出 + public static bool IsSameIPv6Subnet(System.Net.IPAddress ip1, System.Net.IPAddress ip2, int prefixLength) + { + if (ip1.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6 || + ip2.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6) + { + throw new ArgumentException("IP addresses must be IPv6."); + } + + BigInteger ip1Value = new BigInteger(ip1.GetAddressBytes()); + BigInteger ip2Value = new BigInteger(ip2.GetAddressBytes()); + + BigInteger mask = BigInteger.One << (128 - prefixLength); + mask -= BigInteger.One; + mask = ~mask; + + return (ip1Value & mask) == (ip2Value & mask); + } + + /// + /// 获取系统的IPv4地址列表 + /// + /// 命令策略工厂 + /// 取消令牌源 + /// 日志记录器 + /// IPv4地址列表 + public static async Task> CheckAddressIPv4(ICommandStrategyFactory commandStrategyFactory, CancellationTokenSource source) + { + List addrs = new List(); + var inet4result = await commandStrategyFactory.CreateStrategy().ExecuteBufferedAsync("ifconfig | grep 'inet ' | awk '{print $2}'", source); + if (!string.IsNullOrWhiteSpace(inet4result)) + addrs.AddRange(RemoveNewLines(inet4result)); + return addrs; + } + + /// + /// 获取系统的IPv6地址列表 + /// + /// 命令策略工厂 + /// 取消令牌源 + /// 日志记录器 + /// IPv6地址列表 + public static async Task> CheckAddressIPv6(ICommandStrategyFactory commandStrategyFactory, CancellationTokenSource source) + { + List addrs = new List(); + var inet6result = await commandStrategyFactory.CreateStrategy().ExecuteBufferedAsync("ifconfig | grep 'inet6 ' | awk '{print $2}'", source); + if (!string.IsNullOrWhiteSpace(inet6result)) + addrs.AddRange(RemoveNewLines(inet6result)); + return addrs; + } + + /// + /// 获取系统的IPv4地址和子网掩码列表 + /// + /// 命令策略工厂 + /// 取消令牌源 + /// 日志记录器 + /// IPv4地址和子网掩码的元组列表 + public static async Task> CheckAddressIPv4Mask(ICommandStrategyFactory commandStrategyFactory, CancellationTokenSource source) + { + List<(string ipv4, string mask)> addrs = new List<(string ipv4, string mask)>(); + var inet4result = await commandStrategyFactory.CreateStrategy().ExecuteBufferedAsync("ifconfig | grep 'inet ' | awk '{print $2\\\"|\\\"$4}'", source); + if (!string.IsNullOrWhiteSpace(inet4result)) + addrs.AddRange(RemoveNewLines(inet4result).Select(s => (s.Split("|")[0], s.Split("|")[1]))); + return addrs; + } + + /// + /// 获取系统的IPv6地址和前缀长度列表 + /// + /// 命令策略工厂 + /// 取消令牌源 + /// 日志记录器 + /// IPv6地址和前缀长度的元组列表 + public static async Task> CheckAddressIPv6Prefix(ICommandStrategyFactory commandStrategyFactory, CancellationTokenSource source) + { + List<(string ipv6, string Prefix)> addrs = new List<(string ipv6, string Prefix)>(); + var inet6result = await commandStrategyFactory.CreateStrategy().ExecuteBufferedAsync("ifconfig | grep 'inet6 ' | awk '{print $2\\\"|\\\"$4}'", source); + if (!string.IsNullOrWhiteSpace(inet6result)) + addrs.AddRange(RemoveNewLines(inet6result).Select(s => (s.Split("|")[0], s.Split("|")[1]))); + return addrs; + } + + /// + /// 计算两个IP地址的匹配位数 + /// + /// 第一个IP地址 + /// 第二个IP地址 + /// 匹配的位数 + public static int GetMatchingBits(string ip1, string ip2) + { + byte[] bytes1 = System.Net.IPAddress.Parse(ip1).GetAddressBytes(); + byte[] bytes2 = System.Net.IPAddress.Parse(ip2).GetAddressBytes(); + int matchingBits = 0; + for (int i = 0; i < bytes1.Length; i++) + { + int diff = bytes1[i] ^ bytes2[i]; // 异或计算不同位 + for (int bit = 7; bit >= 0; bit--) + { + if ((diff & (1 << bit)) == 0) + matchingBits++; + else + return matchingBits; + } + } + return matchingBits; + } + + /// + /// 移除字符串中的换行符并分割成数组 + /// + /// 输入字符串 + /// 分割后的字符串数组 + private static string[] RemoveNewLines(string input) + { + return input.Split("\n", StringSplitOptions.RemoveEmptyEntries); + } +} \ No newline at end of file diff --git a/CoreAgent.Infrastructure/Services/CellularNetworkService.cs b/CoreAgent.Infrastructure/Services/CellularNetworkService.cs new file mode 100644 index 0000000..c7381b8 --- /dev/null +++ b/CoreAgent.Infrastructure/Services/CellularNetworkService.cs @@ -0,0 +1,154 @@ +using CoreAgent.Domain.Interfaces; +using CoreAgent.Domain.Models; +using Microsoft.Extensions.Logging; +using System.Diagnostics; + +namespace CoreAgent.Infrastructure.Services; + +/// +/// 蜂窝网络服务实现 +/// +public class CellularNetworkService : ICellularNetworkService +{ + private readonly ILogger _logger; + + public CellularNetworkService(ILogger logger) + { + _logger = logger; + } + + public async Task StartAsync(string interfaceName, CellularNetworkConfig config) + { + try + { + _logger.LogInformation("正在启动蜂窝网络接口: {InterfaceName}", interfaceName); + + // 启用网络接口 + var enableCommand = $"netsh interface set interface \"{interfaceName}\" admin=ENABLED"; + await ExecuteCommandAsync(enableCommand); + + // 配置网络接口 + var configCommand = $"netsh interface cellular set profile name=\"{config.Apn}\" interface=\"{interfaceName}\""; + await ExecuteCommandAsync(configCommand); + + _logger.LogInformation("蜂窝网络接口启动成功: {InterfaceName}", interfaceName); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "启动蜂窝网络接口失败: {InterfaceName}", interfaceName); + return false; + } + } + + public async Task StopAsync(string interfaceName) + { + try + { + _logger.LogInformation("正在停止蜂窝网络接口: {InterfaceName}", interfaceName); + + var command = $"netsh interface set interface \"{interfaceName}\" admin=DISABLED"; + await ExecuteCommandAsync(command); + + _logger.LogInformation("蜂窝网络接口停止成功: {InterfaceName}", interfaceName); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "停止蜂窝网络接口失败: {InterfaceName}", interfaceName); + return false; + } + } + + public async Task GetStatusAsync(string interfaceName) + { + try + { + _logger.LogInformation("正在获取蜂窝网络接口状态: {InterfaceName}", interfaceName); + + // 获取接口状态 + var statusCommand = $"netsh interface show interface \"{interfaceName}\""; + var statusResult = await ExecuteCommandAsync(statusCommand); + + // 获取信号强度 + var signalCommand = $"netsh interface cellular show interfaces \"{interfaceName}\""; + var signalResult = await ExecuteCommandAsync(signalCommand); + + var status = new CellularNetworkStatus + { + IsEnabled = statusResult.Contains("已启用", StringComparison.OrdinalIgnoreCase), + ConnectionState = ParseConnectionState(statusResult), + SignalStrength = ParseSignalStrength(signalResult), + CarrierName = ParseCarrierName(signalResult) + }; + + _logger.LogInformation("获取蜂窝网络接口状态成功: {InterfaceName}", interfaceName); + return status; + } + catch (Exception ex) + { + _logger.LogError(ex, "获取蜂窝网络接口状态失败: {InterfaceName}", interfaceName); + throw; + } + } + + private async Task ExecuteCommandAsync(string command) + { + var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "cmd.exe", + Arguments = $"/c {command}", + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + } + }; + + process.Start(); + var output = await process.StandardOutput.ReadToEndAsync(); + var error = await process.StandardError.ReadToEndAsync(); + await process.WaitForExitAsync(); + + if (process.ExitCode != 0) + { + throw new Exception($"命令执行失败: {error}"); + } + + return output; + } + + private string ParseConnectionState(string statusResult) + { + if (statusResult.Contains("已连接", StringComparison.OrdinalIgnoreCase)) + return "已连接"; + if (statusResult.Contains("已断开", StringComparison.OrdinalIgnoreCase)) + return "已断开"; + return "未知"; + } + + private int ParseSignalStrength(string signalResult) + { + // 这里需要根据实际输出格式进行解析 + // 示例实现,实际使用时需要根据具体输出格式调整 + if (signalResult.Contains("信号强度: 强", StringComparison.OrdinalIgnoreCase)) + return 4; + if (signalResult.Contains("信号强度: 中", StringComparison.OrdinalIgnoreCase)) + return 3; + if (signalResult.Contains("信号强度: 弱", StringComparison.OrdinalIgnoreCase)) + return 2; + return 1; + } + + private string ParseCarrierName(string signalResult) + { + // 这里需要根据实际输出格式进行解析 + // 示例实现,实际使用时需要根据具体输出格式调整 + var carrierLine = signalResult.Split('\n') + .FirstOrDefault(line => line.Contains("运营商:", StringComparison.OrdinalIgnoreCase)); + + return carrierLine?.Split(':').LastOrDefault()?.Trim() ?? "未知"; + } +} \ No newline at end of file