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;
    }
}

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?

1 Answers

2
JohanP On Best Solutions

You can't inject into a static constructor. You have a couple of options:

1.) Pass ILogger into the method, hopefully the calling code has it injected.

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>>();

then use Logger in your static method. Personally, I would go for option 1.