Question

When using an IoC container without a static container instance (as this would result in a a service locator anti-pattern), how to resolve types from a static method?

Say, I have a method that reads an object Document from a file:

public class Document {
    // when used with IoC, the Logger gets injected via property injection
    public ILogger Logger { get; set; }
    /* ... */
    public static Document Read (string filePath)
    {
        // need to resolve an ILogger at this point?
        Logger.Info ("reading in {0}", filePath);

        /* ...read in document an return a document instance here ... */

    }
}

The Code is C# but same problem would apply to a Java project.

I know that a simple answer would be "don't use static method", but given the method is stateless i think it is one of the cases where static methods make sense.

Having a singleton IoC container would also help, but this is widely known to be an anti-pattern.

So, what is the way out of the problem?

Was it helpful?

Solution

Although, I can understand why this makes sense to write this function as static, the answer is simply that DI is not going well with static methods that have an associated state. Injected properties are a state of the object and static methods that have an associated state are considered to be an anti-pattern.

DI sometimes forces you to use pure (not anti) patterns.

If you insist on using static method in your case, I can suggest these to cover your options. All are not perfect.

  1. Adding the injected objects as parameters to the function. Document.Read(logger, filePath). If you weren't using an IoC framework, the alternative was: new Document(logger).Read(filepath) which is more or less, the same clumsy code for the caller.
  2. Using a ServiceLocator as you stated.
  3. Add a static initialization method to the class, and inject all of it's dependencies (as static properties). You would have to call this initialization in your application start.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top