ASP .Net Core 中静态方法的依赖注入

Mut*_* PL 1 c# dependency-injection asp.net-core

我已经在启动时在 ServiceCollection 中注册了我的记录器的实现:

services.AddTransient(typeof(ILogger<>), typeof(GenericLogger<>));
Run Code Online (Sandbox Code Playgroud)

通常,我这样做是为了使用构造函数注入:

class DynamoEventProcessor
{
    private readonly IRepository _repository;
    private readonly IDogStatsd _dogStatsd;
    private readonly ILogger<DynamoEventProcessor> _logger;

    public DynamoEventProcessor(IRepository repository, IDogStatsd dogStatsd, ILogger<DynamoEventProcessor> logger)
    {
        _repository = repository;
        _dogStatsd = dogStatsd;
        _logger = logger;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我有一个没有构造函数的类:

public class ProfileContent
{
    public MemoryStream Content { get; set; }
    public string ContentAlgorithm { get; set; }
    public List<Dictionary<string, AttributeValue>> DataKeys { get; set; }
    public long ExpiresUtc { get; set; }
    public long Version { get; set; }
    public long Deleted { get; set; }

    public static Dictionary<string, EncryptedDataAndKeys> GetEncryptedDataAndKeys(Dictionary<string, Dictionary<string, AttributeValue>> profileContentAttributes)
    {
        _logger.LogInformation("Available Keys: " + KeysAsString(keyList));
        _logger.LogInformation("AccountId missing Coporate Data: " + _converter.GetValueFromAttributeValue(attributes["AccountId"]).ToString());
        var encryptedDataAndKeys = new Dictionary<string, EncryptedDataAndKeys>();

        foreach (var item in profileContentAttributes)
        {
            encryptedDataAndKeys.Add(item.Key, GetEncryptedDataAndKey(item.Value));
        }

        return encryptedDataAndKeys;
    }
}
Run Code Online (Sandbox Code Playgroud)

_logger由于空值,我在这里失败了。我理解这个问题,我没有正确注入它。当我在静态方法中使用它而不实例化对象时,如何注入它?

Joh*_*anP 6

您不能注入静态构造函数。你有几个选择:

1.)ILogger传入方法,希望调用代码已注入它。

2)有一个静态属性ILoggerProfileContent,然后在你的Startup文件,在该Configure方法中,初始化即

ProfileContent.Logger = app.ApplicationServices.GetService<ILogger<ProfileContent>>();
Run Code Online (Sandbox Code Playgroud)

然后Logger在您的静态方法中使用。就我个人而言,我会选择选项 1。

  • 选项 2 是服务定位器反模式。它还对 Logger 的创建和分配进行黑箱处理,并且作为一般规则,我不喜欢静态属性。 (3认同)
  • 我唯一可以添加的是:3)摆脱静态,在 DI 中使用单例注册,这个类真的需要是静态的吗? (2认同)