Browse Source

Update project structure and add new features

master
root 7 days ago
parent
commit
d38d939f0e
  1. 80
      CoreAgent.API/Controllers/BaseApiController.cs
  2. 48
      CoreAgent.API/Controllers/CellularNetworkController.cs
  3. 2
      CoreAgent.API/CoreAgent.API.csproj
  4. 15
      CoreAgent.API/Startup.cs
  5. 308
      CoreAgent.API/logs/log-20250611.txt
  6. 41
      CoreAgent.Application/Commands/CellularNetwork/GetCellularNetworkStatusCommand.cs
  7. 20
      CoreAgent.Application/Commands/CellularNetwork/StartCellularNetworkCommand.cs
  8. 33
      CoreAgent.Application/Commands/CellularNetwork/StartCellularNetworkCommandHandler.cs
  9. 14
      CoreAgent.Application/Commands/CellularNetwork/StopCellularNetworkCommand.cs
  10. 9
      CoreAgent.Application/CoreAgent.Application.csproj
  11. 48
      CoreAgent.Application/Handlers/CellularNetwork/GetCellularNetworkStatusCommandHandler.cs
  12. 48
      CoreAgent.Application/Handlers/CellularNetwork/StartCellularNetworkCommandHandler.cs
  13. 48
      CoreAgent.Application/Handlers/CellularNetwork/StopCellularNetworkCommandHandler.cs
  14. 1
      CoreAgent.Domain/CoreAgent.Domain.csproj
  15. 31
      CoreAgent.Domain/Interfaces/ICellularNetworkService.cs
  16. 28
      CoreAgent.Domain/Interfaces/ICommandStrategyFactory.cs
  17. 49
      CoreAgent.Domain/Models/ApiActionResult.cs
  18. 58
      CoreAgent.Domain/Models/ApiResponse.cs
  19. 22
      CoreAgent.Domain/Models/CellularNetworkConfig.cs
  20. 27
      CoreAgent.Domain/Models/CellularNetworkStatus.cs
  21. 44
      CoreAgent.Infrastructure/Command/CommandStrategyFactory.cs
  22. 123
      CoreAgent.Infrastructure/Command/LinuxCommandStrategy.cs
  23. 123
      CoreAgent.Infrastructure/Command/WindowsCommandStrategy.cs
  24. 1
      CoreAgent.Infrastructure/CoreAgent.Infrastructure.csproj
  25. 27
      CoreAgent.Infrastructure/Extensions/ServiceCollectionExtensions.cs
  26. 168
      CoreAgent.Infrastructure/Network/IPAddressUtils.cs
  27. 154
      CoreAgent.Infrastructure/Services/CellularNetworkService.cs

80
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<BaseApiController> _logger;
protected BaseApiController(IMediator mediator, ILogger<BaseApiController> logger)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
protected async Task<IActionResult> HandleRequest<TRequest, TResponse>(TRequest request)
where TRequest : IRequest<TResponse>
{
try
{
_logger.LogInformation("Handling request of type {RequestType}", typeof(TRequest).Name);
var response = await _mediator.Send(request);
return new ApiActionResult<TResponse>(ApiResponse<TResponse>.CreateSuccess(response));
}
catch (Exception ex)
{
_logger.LogError(ex, "Error handling request of type {RequestType}", typeof(TRequest).Name);
return new ApiActionResult<TResponse>(
ApiResponse<TResponse>.CreateError(ex.Message),
HttpStatusCode.InternalServerError
);
}
}
protected async Task<IActionResult> HandleRequest<TRequest>(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>(T data, string message = null)
{
return new ApiActionResult<T>(ApiResponse<T>.CreateSuccess(data, message));
}
protected IActionResult Success(string message = null)
{
return new ApiActionResult(ApiResponse.CreateSuccess(message));
}
protected IActionResult Error(string message, List<string> errors = null, HttpStatusCode statusCode = HttpStatusCode.BadRequest)
{
return new ApiActionResult(ApiResponse.CreateError(message, errors), statusCode);
}
protected IActionResult Error<T>(string message, List<string> errors = null, HttpStatusCode statusCode = HttpStatusCode.BadRequest)
{
return new ApiActionResult<T>(ApiResponse<T>.CreateError(message, errors), statusCode);
}
}
}

48
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;
/// <summary>
/// 蜂窝网络控制器
/// </summary>
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class CellularNetworkController : BaseApiController
{
private readonly ILogger<CellularNetworkController> _logger;
public CellularNetworkController(
IMediator mediator,
ILogger<CellularNetworkController> logger) : base(mediator, logger)
{
_logger = logger;
}
/// <summary>
/// 启动蜂窝网络
/// </summary>
/// <param name="command">启动命令</param>
/// <returns>操作结果</returns>
[HttpPost("start")]
public async Task<IActionResult> Start([FromBody] StartCellularNetworkCommand command)
{
_logger.LogInformation("收到启动蜂窝网络请求: {InterfaceName}", command.InterfaceName);
return await HandleRequest<StartCellularNetworkCommand, bool>(command);
}
/// <summary>
/// 停止蜂窝网络
/// </summary>
/// <param name="command">停止命令</param>
/// <returns>操作结果</returns>
[HttpPost("stop")]
public async Task<IActionResult> Stop([FromBody] StopCellularNetworkCommand command)
{
_logger.LogInformation("收到停止蜂窝网络请求: {InterfaceName}", command.InterfaceName);
return await HandleRequest<StopCellularNetworkCommand, bool>(command);
}
}

2
CoreAgent.API/CoreAgent.API.csproj

@ -11,11 +11,13 @@
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.1.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="5.1.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="5.1.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageReference Include="MediatR" Version="12.2.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" /> <PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\CoreAgent.Application\CoreAgent.Application.csproj" />
<ProjectReference Include="..\CoreAgent.Infrastructure\CoreAgent.Infrastructure.csproj" /> <ProjectReference Include="..\CoreAgent.Infrastructure\CoreAgent.Infrastructure.csproj" />
</ItemGroup> </ItemGroup>

15
CoreAgent.API/Startup.cs

@ -1,9 +1,6 @@
using CoreAgent.Infrastructure.Extensions; using CoreAgent.Infrastructure.Extensions;
using CoreAgent.Infrastructure.Logging; using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog; using Serilog;
namespace CoreAgent.API namespace CoreAgent.API
@ -21,10 +18,17 @@ namespace CoreAgent.API
public void ConfigureServices(IServiceCollection services) 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.AddInfrastructure(Configuration);
// 添加控制器 // 添加控制器
services.AddControllers(); services.AddControllers();
@ -87,6 +91,7 @@ namespace CoreAgent.API
.AddApiVersioningExtension(config) .AddApiVersioningExtension(config)
.AddRequestLogging(config) .AddRequestLogging(config)
.AddAuthorization() .AddAuthorization()
.AddCommandCustomService()
.AddSwaggerGen(); .AddSwaggerGen();
} }

308
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.<Main>$(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.<Main>$(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.<Main>$(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.<Handle>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.<Main>$(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.<Handle>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.<Main>$(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.<Main>$(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.<Main>$(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

41
CoreAgent.Application/Commands/CellularNetwork/GetCellularNetworkStatusCommand.cs

@ -0,0 +1,41 @@
using CoreAgent.Domain.Models;
using MediatR;
namespace CoreAgent.Application.Commands.CellularNetwork;
/// <summary>
/// 获取蜂窝网络状态命令
/// </summary>
public class GetCellularNetworkStatusCommand : IRequest<CellularNetworkStatus>
{
/// <summary>
/// 网络接口名称
/// </summary>
public string InterfaceName { get; set; }
}
/// <summary>
/// 蜂窝网络状态
/// </summary>
public class CellularNetworkStatus
{
/// <summary>
/// 是否启用
/// </summary>
public bool IsEnabled { get; set; }
/// <summary>
/// 连接状态
/// </summary>
public string ConnectionState { get; set; }
/// <summary>
/// 信号强度
/// </summary>
public int SignalStrength { get; set; }
/// <summary>
/// 运营商名称
/// </summary>
public string CarrierName { get; set; }
}

20
CoreAgent.Application/Commands/CellularNetwork/StartCellularNetworkCommand.cs

@ -0,0 +1,20 @@
using CoreAgent.Domain.Models;
using MediatR;
namespace CoreAgent.Application.Commands.CellularNetwork;
/// <summary>
/// 启动蜂窝网络命令
/// </summary>
public class StartCellularNetworkCommand : IRequest<bool>
{
/// <summary>
/// 网络接口名称
/// </summary>
public string InterfaceName { get; set; }
/// <summary>
/// 网络配置
/// </summary>
public CellularNetworkConfig Config { get; set; }
}

33
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<StartCellularNetworkCommand, bool>
{
private readonly ICellularNetworkService _cellularNetworkService;
private readonly ILogger<StartCellularNetworkCommandHandler> _logger;
public StartCellularNetworkCommandHandler(
ICellularNetworkService cellularNetworkService,
ILogger<StartCellularNetworkCommandHandler> logger)
{
_cellularNetworkService = cellularNetworkService;
_logger = logger;
}
public async Task<bool> 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;
}
}
}

14
CoreAgent.Application/Commands/CellularNetwork/StopCellularNetworkCommand.cs

@ -0,0 +1,14 @@
using MediatR;
namespace CoreAgent.Application.Commands.CellularNetwork;
/// <summary>
/// 停止蜂窝网络命令
/// </summary>
public class StopCellularNetworkCommand : IRequest<bool>
{
/// <summary>
/// 网络接口名称
/// </summary>
public string InterfaceName { get; set; }
}

9
CoreAgent.Application/CoreAgent.Application.csproj

@ -6,4 +6,13 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="MediatR" Version="12.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CoreAgent.Domain\CoreAgent.Domain.csproj" />
</ItemGroup>
</Project> </Project>

48
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;
/// <summary>
/// 获取蜂窝网络状态命令处理器
/// </summary>
public class GetCellularNetworkStatusCommandHandler : IRequestHandler<GetCellularNetworkStatusCommand, CellularNetworkStatus>
{
private readonly ICellularNetworkService _cellularNetworkService;
private readonly ILogger<GetCellularNetworkStatusCommandHandler> _logger;
public GetCellularNetworkStatusCommandHandler(
ICellularNetworkService cellularNetworkService,
ILogger<GetCellularNetworkStatusCommandHandler> logger)
{
_cellularNetworkService = cellularNetworkService;
_logger = logger;
}
public async Task<CellularNetworkStatus> 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;
}
}
}

48
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;
/// <summary>
/// 启动蜂窝网络命令处理器
/// </summary>
public class StartCellularNetworkCommandHandler : IRequestHandler<StartCellularNetworkCommand, bool>
{
private readonly ICellularNetworkService _cellularNetworkService;
private readonly ILogger<StartCellularNetworkCommandHandler> _logger;
public StartCellularNetworkCommandHandler(
ICellularNetworkService cellularNetworkService,
ILogger<StartCellularNetworkCommandHandler> logger)
{
_cellularNetworkService = cellularNetworkService;
_logger = logger;
}
public async Task<bool> 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;
}
}
}

48
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;
/// <summary>
/// 停止蜂窝网络命令处理器
/// </summary>
public class StopCellularNetworkCommandHandler : IRequestHandler<StopCellularNetworkCommand, bool>
{
private readonly ICellularNetworkService _cellularNetworkService;
private readonly ILogger<StopCellularNetworkCommandHandler> _logger;
public StopCellularNetworkCommandHandler(
ICellularNetworkService cellularNetworkService,
ILogger<StopCellularNetworkCommandHandler> logger)
{
_cellularNetworkService = cellularNetworkService;
_logger = logger;
}
public async Task<bool> 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;
}
}
}

1
CoreAgent.Domain/CoreAgent.Domain.csproj

@ -7,6 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
</ItemGroup> </ItemGroup>

31
CoreAgent.Domain/Interfaces/ICellularNetworkService.cs

@ -0,0 +1,31 @@
using CoreAgent.Domain.Models;
namespace CoreAgent.Domain.Interfaces;
/// <summary>
/// 蜂窝网络服务接口
/// </summary>
public interface ICellularNetworkService
{
/// <summary>
/// 启动蜂窝网络
/// </summary>
/// <param name="interfaceName">网络接口名称</param>
/// <param name="config">网络配置</param>
/// <returns>操作是否成功</returns>
Task<bool> StartAsync(string interfaceName, CellularNetworkConfig config);
/// <summary>
/// 停止蜂窝网络
/// </summary>
/// <param name="interfaceName">网络接口名称</param>
/// <returns>操作是否成功</returns>
Task<bool> StopAsync(string interfaceName);
/// <summary>
/// 获取蜂窝网络状态
/// </summary>
/// <param name="interfaceName">网络接口名称</param>
/// <returns>网络状态信息</returns>
Task<CellularNetworkStatus> GetStatusAsync(string interfaceName);
}

28
CoreAgent.Domain/Interfaces/ICommandStrategyFactory.cs

@ -0,0 +1,28 @@
namespace CoreAgent.Domain.Interfaces;
/// <summary>
/// 命令策略工厂接口
/// </summary>
public interface ICommandStrategyFactory
{
/// <summary>
/// 创建命令策略
/// </summary>
/// <returns>命令策略实例</returns>
ICommandStrategy CreateStrategy();
}
/// <summary>
/// 命令策略接口
/// </summary>
public interface ICommandStrategy
{
/// <summary>
/// 执行命令并返回缓冲结果
/// </summary>
/// <param name="command">要执行的命令</param>
/// <param name="source">取消令牌源</param>
/// <param name="logger">日志记录器</param>
/// <returns>命令执行结果</returns>
Task<string> ExecuteBufferedAsync(string command, CancellationTokenSource source);
}

49
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<T> : IActionResult
{
private readonly ApiResponse<T> _response;
private readonly HttpStatusCode _statusCode;
public ApiActionResult(ApiResponse<T> 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);
}
}
}

58
CoreAgent.Domain/Models/ApiResponse.cs

@ -0,0 +1,58 @@
namespace CoreAgent.Domain.Models
{
public class ApiResponse<T>
{
public bool Success { get; set; }
public string? Message { get; set; }
public T? Data { get; set; }
public List<string> Errors { get; set; }
public ApiResponse()
{
Success = true;
Errors = new List<string>();
}
public static ApiResponse<T> CreateSuccess(T data, string? message = null)
{
return new ApiResponse<T>
{
Success = true,
Data = data,
Message = message
};
}
public static ApiResponse<T> CreateError(string message, List<string>? errors = null)
{
return new ApiResponse<T>
{
Success = false,
Message = message,
Errors = errors ?? new List<string>()
};
}
}
public class ApiResponse : ApiResponse<object>
{
public new static ApiResponse CreateSuccess(string? message = null)
{
return new ApiResponse
{
Success = true,
Message = message
};
}
public new static ApiResponse CreateError(string message, List<string>? errors = null)
{
return new ApiResponse
{
Success = false,
Message = message,
Errors = errors ?? new List<string>()
};
}
}
}

22
CoreAgent.Domain/Models/CellularNetworkConfig.cs

@ -0,0 +1,22 @@
namespace CoreAgent.Domain.Models;
/// <summary>
/// 蜂窝网络配置
/// </summary>
public class CellularNetworkConfig
{
/// <summary>
/// APN名称
/// </summary>
public string Apn { get; set; }
/// <summary>
/// 用户名
/// </summary>
public string Username { get; set; }
/// <summary>
/// 密码
/// </summary>
public string Password { get; set; }
}

27
CoreAgent.Domain/Models/CellularNetworkStatus.cs

@ -0,0 +1,27 @@
namespace CoreAgent.Domain.Models;
/// <summary>
/// 蜂窝网络状态
/// </summary>
public class CellularNetworkStatus
{
/// <summary>
/// 是否启用
/// </summary>
public bool IsEnabled { get; set; }
/// <summary>
/// 连接状态
/// </summary>
public string ConnectionState { get; set; }
/// <summary>
/// 信号强度
/// </summary>
public int SignalStrength { get; set; }
/// <summary>
/// 运营商名称
/// </summary>
public string CarrierName { get; set; }
}

44
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;
/// <summary>
/// 命令策略工厂实现
/// </summary>
public class CommandStrategyFactory : ICommandStrategyFactory
{
private readonly ILogger<CommandStrategyFactory> _logger;
private readonly ILoggerFactory _loggerFactory;
public CommandStrategyFactory(ILogger<CommandStrategyFactory> logger, ILoggerFactory loggerFactory)
{
_logger = logger;
_loggerFactory = loggerFactory;
}
/// <summary>
/// 创建适合当前操作系统的命令策略
/// </summary>
/// <returns>命令策略实例</returns>
/// <exception cref="PlatformNotSupportedException">当操作系统不是Windows或Linux时抛出</exception>
public ICommandStrategy CreateStrategy()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
_logger.LogInformation("Creating Windows command strategy");
return new WindowsCommandStrategy(_loggerFactory.CreateLogger<WindowsCommandStrategy>());
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
_logger.LogInformation("Creating Linux command strategy");
return new LinuxCommandStrategy(_loggerFactory.CreateLogger<LinuxCommandStrategy>());
}
else
{
_logger.LogError("Unsupported operating system");
throw new PlatformNotSupportedException("Only Windows and Linux are supported.");
}
}
}

123
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;
/// <summary>
/// Linux命令策略实现
/// </summary>
public class LinuxCommandStrategy : ICommandStrategy
{
private readonly ILogger<LinuxCommandStrategy> _logger;
public LinuxCommandStrategy(ILogger<LinuxCommandStrategy> logger)
{
_logger = logger;
}
public async Task ExecuteBufferedAsync(string arguments, Action<string> 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<string> 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<bool> 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<string> 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<bool> 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;
}
}
}

123
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;
/// <summary>
/// Windows命令策略实现
/// </summary>
public class WindowsCommandStrategy : ICommandStrategy
{
private readonly ILogger<WindowsCommandStrategy> _logger;
public WindowsCommandStrategy(ILogger<WindowsCommandStrategy> logger)
{
_logger = logger;
}
public async Task ExecuteBufferedAsync(string arguments, Action<string> 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<string> 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<bool> 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<string> 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<bool> 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;
}
}
}

1
CoreAgent.Infrastructure/CoreAgent.Infrastructure.csproj

@ -7,6 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="CliWrap" Version="3.9.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.1.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="5.1.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="5.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />

27
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;
/// <summary>
/// 服务集合扩展方法
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// 添加命令策略服务
/// </summary>
/// <param name="services">服务集合</param>
/// <returns>服务集合</returns>
public static IServiceCollection AddCommandCustomService(this IServiceCollection services)
{
// 注册命令策略工厂
services.AddSingleton<ICommandStrategyFactory, CommandStrategyFactory>();
// 注册 ICellularNetworkService
services.AddScoped<ICellularNetworkService, CellularNetworkService>();
return services;
}
}

168
CoreAgent.Infrastructure/Network/IPAddressUtils.cs

@ -0,0 +1,168 @@
using System.Numerics;
using CoreAgent.Domain.Interfaces;
namespace CoreAgent.Infrastructure.Network;
/// <summary>
/// 提供IP地址相关的工具方法
/// </summary>
public static class IPAddressUtils
{
/// <summary>
/// 检查两个IPv4地址是否在同一个子网内
/// </summary>
/// <param name="ip1">第一个IP地址</param>
/// <param name="ip2">第二个IP地址</param>
/// <param name="subnetMask">子网掩码</param>
/// <returns>如果两个IP地址在同一个子网内返回true,否则返回false</returns>
/// <exception cref="ArgumentException">当IP地址或子网掩码不是IPv4格式时抛出</exception>
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));
}
/// <summary>
/// 检查两个IPv6地址是否在同一个子网内
/// </summary>
/// <param name="ip1">第一个IP地址</param>
/// <param name="ip2">第二个IP地址</param>
/// <param name="prefixLength">前缀长度</param>
/// <returns>如果两个IP地址在同一个子网内返回true,否则返回false</returns>
/// <exception cref="ArgumentException">当IP地址不是IPv6格式时抛出</exception>
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);
}
/// <summary>
/// 获取系统的IPv4地址列表
/// </summary>
/// <param name="commandStrategyFactory">命令策略工厂</param>
/// <param name="source">取消令牌源</param>
/// <param name="logger">日志记录器</param>
/// <returns>IPv4地址列表</returns>
public static async Task<IEnumerable<string>> CheckAddressIPv4(ICommandStrategyFactory commandStrategyFactory, CancellationTokenSource source)
{
List<string> addrs = new List<string>();
var inet4result = await commandStrategyFactory.CreateStrategy().ExecuteBufferedAsync("ifconfig | grep 'inet ' | awk '{print $2}'", source);
if (!string.IsNullOrWhiteSpace(inet4result))
addrs.AddRange(RemoveNewLines(inet4result));
return addrs;
}
/// <summary>
/// 获取系统的IPv6地址列表
/// </summary>
/// <param name="commandStrategyFactory">命令策略工厂</param>
/// <param name="source">取消令牌源</param>
/// <param name="logger">日志记录器</param>
/// <returns>IPv6地址列表</returns>
public static async Task<IEnumerable<string>> CheckAddressIPv6(ICommandStrategyFactory commandStrategyFactory, CancellationTokenSource source)
{
List<string> addrs = new List<string>();
var inet6result = await commandStrategyFactory.CreateStrategy().ExecuteBufferedAsync("ifconfig | grep 'inet6 ' | awk '{print $2}'", source);
if (!string.IsNullOrWhiteSpace(inet6result))
addrs.AddRange(RemoveNewLines(inet6result));
return addrs;
}
/// <summary>
/// 获取系统的IPv4地址和子网掩码列表
/// </summary>
/// <param name="commandStrategyFactory">命令策略工厂</param>
/// <param name="source">取消令牌源</param>
/// <param name="logger">日志记录器</param>
/// <returns>IPv4地址和子网掩码的元组列表</returns>
public static async Task<List<(string ipv4, string mask)>> 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;
}
/// <summary>
/// 获取系统的IPv6地址和前缀长度列表
/// </summary>
/// <param name="commandStrategyFactory">命令策略工厂</param>
/// <param name="source">取消令牌源</param>
/// <param name="logger">日志记录器</param>
/// <returns>IPv6地址和前缀长度的元组列表</returns>
public static async Task<List<(string ipv6, string Prefix)>> 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;
}
/// <summary>
/// 计算两个IP地址的匹配位数
/// </summary>
/// <param name="ip1">第一个IP地址</param>
/// <param name="ip2">第二个IP地址</param>
/// <returns>匹配的位数</returns>
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;
}
/// <summary>
/// 移除字符串中的换行符并分割成数组
/// </summary>
/// <param name="input">输入字符串</param>
/// <returns>分割后的字符串数组</returns>
private static string[] RemoveNewLines(string input)
{
return input.Split("\n", StringSplitOptions.RemoveEmptyEntries);
}
}

154
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;
/// <summary>
/// 蜂窝网络服务实现
/// </summary>
public class CellularNetworkService : ICellularNetworkService
{
private readonly ILogger<CellularNetworkService> _logger;
public CellularNetworkService(ILogger<CellularNetworkService> logger)
{
_logger = logger;
}
public async Task<bool> 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<bool> 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<CellularNetworkStatus> 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<string> 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() ?? "未知";
}
}
Loading…
Cancel
Save