[英]Dependency Injection on static method in ASP .Net Core
我已經在啟動時在ServiceCollection中注冊了記錄器的實現:
services.AddTransient(typeof(ILogger<>), typeof(GenericLogger<>));
通常,我這樣做是使用構造函數注入的:
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;
}
}
但是我有一個沒有構造函數的類:
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
在此處由於null而失敗。 我了解這個問題,因為我沒有正確注射它。 在靜態方法中使用它而不實例化對象時如何注入它?
您不能注入靜態構造函數。 您有兩種選擇:
1.)將ILogger
傳遞到方法中,希望調用代碼已將其注入。
2)有一個靜態屬性ILogger
上ProfileContent
,然后在你的Startup
文件,在Configure
方法,對其進行初始化即
ProfileContent.Logger = app.ApplicationServices.GetService<ILogger<ProfileContent>>();
然后在您的靜態方法中使用Logger
。 就個人而言,我會選擇選項1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.