How to inject dependency to static class

I've been making simple logger class with DI but I have some problem and question.

There is a problem. If I make a logger class with DI. I should use it like this whenever I use it.

var logger = new LogService(new FileLogger());
logger.WriteLine("message");

I want to make it to static class, but there is no way to inject dependency by constructor in static class.

So, I change it like this.

public static class LogService()
{
    private static readonly ILoggable _logger;
    static LogService()
    {
         _logger = new FileLogger();
    }
}

I think this is so weird. This is not DI..

Isn't there a good way to inject dependency to static class?


Solution 1:

Dependency Injection, as a practice, is meant to introduce abstractions (or seams) to decouple volatile dependencies. A volatile dependency is a class or module that, among other things, can contain nondeterministic behavior or in general is something you which to be able to replace or intercept.

For a more detailed discussion about volatile dependencies, see section 1.3.2 of this freely readable introduction of my book.

Because your FileLogger writes to disk, it contains nondeterministic behavior. For this reason you introduced the ILoggable abstraction. This allows consumers to be decoupled from the FileLogger implementation.

To be able to successfully decouple a consumer from its volatile dependency, however, you need to inject that dependency into the consumer. There are three common patterns to choose from:

  • Constructor Injection—Dependencies are statically defined as list of parameters to the class's instance constructor.
  • Property Injection—Dependencies are injected into the consumer via writable instance properties.
  • Method Injection—Dependencies are injected into the consumer as method parameters.

Both Constructor Injection and Property Injection are applied inside the startup path of the application (a.k.a. the Composition Root) and require the consumer to store the dependency in a private field for later reuse. This requires the constructor and property to be instance members, i.e. non-static. Static constructors can't have any parameters and static properties lead to the Ambient Context anti-pattern (see section 5.3), and Temporal Coupling. This hinders testability and maintainability.

Method injection, on the other hand, is applied outside the Composition Root and it does not store any supplied dependency, but instead merely uses it.

Method injection is, therefore, the only of the three patterns that can be applied to both instance and static methods.

In that case, the method's consumer must supply the dependency. This does mean, however, that the consumer itself must have been supplied with that dependency either through constructor, property, or method injection.

Your example of the static LogService that created FileLogger inside its constructor is a great example of tightly coupled code. This is known as the Control Freak anti-pattern (section 5.1) or in general can be seen as a DIP violation. This is the opposite of DI.

To prevent tight coupling of volatile dependencies, the best is to make LogService non-static and inject its volatile dependencies into its sole public constructor.

Solution 2:

It doesn't make sense to use dependency injection (DI) with a static class. Instead of DI, simply add an initialization method to your static class and pass in the dependency.

public static class LogService
{
    private static ILoggable _logger;

    public static ILoggable Logger
    {
        get
        {
             return _logger;
        }
    }

    public static void InitLogger(ILoggable logger)
    {
         _logger = logger;
    }
}

To use the logger, just make sure to call InitLogger() first:

LogService.InitLogger(new FileLogger());
LogService.Logger.WriteLine("message");

Solution 3:

You could use Lazy initialization for any object you need to inject to a static class.

https://docs.microsoft.com/en-us/dotnet/api/system.lazy-1?view=net-5.0

This would allow you to pass around static objects that can be shared across running instances and other classes/methods that need to use those objects. An example would be an HttpClient that you want to share across your entire application. You can lazy initialize the HttpClient inside of a static class and refer to the static class to get the HttpClient.

Here's another example using a CosmosDB client: https://docs.microsoft.com/en-us/azure/azure-functions/manage-connections?tabs=csharp#azure-cosmos-db-clients