分离依赖注入C#的派生和基类之间的记录 与SO相似(基本和派生类中的依赖项注入),我希望将基础类别和派生类的“类别”分开。 我尝试了带有两个答案的变体...

问题描述 投票:0回答:1
Base类:

到目前为止,最好的努力是尝试正确地进行施放,但这无效。 public abstract class LifetimeEventsHostedService : IHostedService { private readonly ILogger<LifetimeEventsHostedService> _logger; protected LifetimeEventsHostedService(ILogger logger) { _logger = (ILogger<LifetimeEventsHostedService>)logger; } public virtual Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("LifetimeEventsHostedService.StartAsync has been called"); } } derfived班级:

public class DerivedHostedService: LifetimeEventsHostedService
{
  private readonly ILogger<DerivedHostedService> _logger;

  public DerivedHostedService(ILogger<DerivedHostedService> logger) : base(logger) 
  {
    _logger = logger;
  }

  public override async Task StartAsync(CancellationToken cancellationToken)
  {
    await base.StartAsync(cancellationToken);
    _logger.LogInformation("StartAsync completed");
  }
}

现在,控制台日志显示如下:

info: PlayerService.Services.HostedServices.DerivedHostedService[0] // Should show as base class category LifetimeEventsHostedService.StartAsync has been called // Hacky workaround to include base category in the message info: PlayerService.Services.HostedServices.DerivedHostedService[0] // Obviously (correctly) showing correct in derived class StartAsync completed info: PlayerService.Services.HostedServices.DerivedHostedService[0] // Should show as base class category LifetimeEventsHostedService.OnStarted has been called // Hacky workaround to include base category in the message info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down.

我在上面完成的工作方式,但是我想找到一种将
type
(类别)设置为基类的方法在基类中的名称),而不是在可能的情况下保持两者之间的记录分离。

您可以在派生类中要求两个登录器:

public DerivedHostedService( ILogger<DerivedHostedService> logger, ILogger<LifetimeEventsHostedService> baseLogger) : base(baseLogger) {}
    

我在这里遇到同样的问题,想知道您是否找到了更好的方法,而不是接受的答案,因为您提到这不是最好的练习?

    

如果您最终需要在基类中需要多个服务,但是不希望每个派生的类都必须将它们全部召集。我个人会避免这种情况,但是它可能会绕过您收到的警告,尽管我个人认为您“将两者分开非常具体”。
public DerivedHostedService( ILogger<DerivedHostedService> logger, IServiceProvider services) : base(services) {} public BaseHostedService( IServiceProvider services) { var logger = services.GetRequiredService<ILogger<BaseHostedService>>(); // etc }

c# logging dependency-injection
1个回答
3
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.