在.NET Core中对静态方法的依赖注入 [英] Dependency Injection on static method in ASP .Net Core
问题描述
在启动时,我已经在ServiceCollection中注册了记录器的实现:
I have registered the implementation of my logger in ServiceCollection in the start up:
services.AddTransient(typeof(ILogger<>), typeof(GenericLogger<>));
通常,我这样做是使用构造函数注入的:
Usually, I do this to inject using Constructor:
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;
}
}
但是我有一个没有构造函数的类:
But I have a class where there is no constructor:
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;
}
}
我的 _logger
由于失败而在此处失败.我了解这个问题,因为我没有正确注射它.在不实例化对象的情况下以静态方法使用它时如何注入它?
My _logger
failed here due to null. I understand the problem, that I didn't inject it properly. How can I inject it when I use it in static method without instantiating an object?
推荐答案
您不能注入静态构造函数.您有两种选择:
You can't inject into a static constructor. You have a couple of options:
1.)将 ILogger
传递到方法中,希望调用代码已将其注入.
1.) Pass ILogger
into the method, hopefully the calling code has it injected.
2.)在 ProfileContent
上具有 ILogger
的静态属性,然后在 Startup
文件中的 Configure 中具有静态属性code>方法,将其初始化,即
2.) Have a static property for ILogger
on ProfileContent
and then in your Startup
file, in the Configure
method, initialize it i.e.
ProfileContent.Logger = app.ApplicationServices.GetService<ILogger<ProfileContent>>();
然后在您的静态方法中使用 Logger
.就个人而言,我会选择选项1.
then use Logger
in your static method. Personally, I would go for option 1.
这篇关于在.NET Core中对静态方法的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!