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由于空值,我在这里失败了。我理解这个问题,我没有正确注入它。当我在静态方法中使用它而不实例化对象时,如何注入它?
您不能注入静态构造函数。你有几个选择:
1.)ILogger传入方法,希望调用代码已注入它。
2)有一个静态属性ILogger上ProfileContent,然后在你的Startup文件,在该Configure方法中,初始化即
ProfileContent.Logger = app.ApplicationServices.GetService<ILogger<ProfileContent>>();
Run Code Online (Sandbox Code Playgroud)
然后Logger在您的静态方法中使用。就我个人而言,我会选择选项 1。