Wednesday, December 18, 2013

Dependency Injection Automatic Factories

One of the features of the Unity Application Block is automatic factory construction. What this means is if you configure Unity to resolve type Abc, then Unity also knows how to resolve Func<Abc>.

This allows using lazy evaluation of injected properties. The code below shows how to use an automatic factory.

private Abc abc = null;
public Func FuncAbc { get; set; }
protected Abc Abc
{
    get
    {
        if (abc == null && FuncAbc != null) abc = FuncAbc();
        return abc;
    }
}

When the code accesses Abc the getter checks the underlying private field abc to see if it is null. If it is null, then the code checks to make sure the factory FuncAbc is not null. If the factory is not null then it creates a new instance by calling the factory FuncAbc.

No comments: