Dependency Injection Patterns

Choosing the right pattern for implementing dependency injection is an important task and can affect your class’s usability and functionality. In this post I’ll overview 3 patterns of implementing dependency injection - constructor injection, property injection, builder (Joshua Bloch’s pattern, not GoF pattern). For demonstration purposes we will work with a class called TextTranslator, that requires 3 dependencies: TextReader, TranslationService and TextWriter:

public class TextTranslator
{
    protected TextReader textReader;
    protected TranslationService translationService;
    protected TextWriter textWriter;    
}

The sample code will be written in C#, but the examples are applicable to Java and other object oriented languages.

[Read More]

Disposing Objects Created by DI Container

The general rule says that if you created an object, then it is your responsibility to dispose it. Things get a bit tricky when objects are created by a dependency injection container. The responsibility of containers is to construct objects and inject the dependencies they need. An error I’ve seen people doing again and again is to dispose objects that were injected into an object via constructor or property injection. Consider the class “Foo” that requires an instance of class “Bar”:

public class Foo : IDisposable {  
    protected Bar bar;  
    public Foo(Bar bar) {  
        this.bar = bar;  
    }  
    public void Dispose() {  
        bar.Dispose();  
    }  
}  

public class Program {  
    static void Main() {  
        var foo = container.Resolve<Foo>();  
        ...  
        foo.Dispose();  
    }  
}  

The problem with this approach is that the “Foo” class will know too much about the environment it runs in. At least it will think it does. An instance of “Foo” can’t and shouldn’t know who passed in the instance of “Bar”, and what he intends to do with it after the instance of “Foo” will be disposed.

[Read More]