簡體   English   中英

.NET Core中對靜態方法的依賴注入

[英]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)有一個靜態屬性ILoggerProfileContent ,然后在你的Startup文件,在Configure方法,對其進行初始化即

ProfileContent.Logger = app.ApplicationServices.GetService<ILogger<ProfileContent>>();

然后在您的靜態方法中使用Logger 就個人而言,我會選擇選項1。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM