castle-windsor Abstract Factory Simple abstract factory - factory takes no parameters


Example

Scenario: You need to resolve a dependency when a method is called, not in the constructor.

Solution: Inject an abstract factory into the constructor. When the method is called, it requests the dependency from the abstract factory, which in turn resolves it from the container. (Your class depends on the factory but never calls the container itself.)

Declare an interface for your factory*:

public interface IFooFactory
{
    IFoo CreateFoo();
    void Release(IFoo foo);
}

Add the TypedFactoryFacility to your container:

container.AddFacility<TypedFactoryFacility>();

Instruct the container to use the TypedFactoryFacility to resolve dependencies on IFooFactory:

container.Register(
    Component.For<IFooFactory>().AsFactory(),
    Component.For<IFoo, MyFooImplementation>());

You don't need to create an instance of a factory. Windsor does that.

You can now inject the factory into a class and use it like this:

public class NeedsFooFactory
{
    private readonly IFooFactory _fooFactory;

    public NeedsFooFactory(IFooFactory fooFactory)
    {
        _fooFactory = fooFactory;
    }

    public void MethodThatNeedsFoo()
    {
        var foo = _fooFactory.CreateFoo();
        foo.DoWhatAFooDoes();
        _fooFactory.Release(foo);
    }
}

Calling the Release method causes the container to release the component it resolved. Otherwise it won't be released until _fooFactory is released (which is whenever NeedsFooFactory is released.)

*Windsor infers which method is the "create" method and which is the "release" method. If a method returns something then it's assumed that the container must resolve it. If a method returns nothing (void) then it's the "release" method.