Can’t combine Factory / DI

The default solution to DI when you can’t wire up a concrete type at registration time is to use an Abstract Factory

In your case, I would define an IFooFactory interface:

public interface IFooFactory
{
    Foo Create(DomainClass dc);
}

This will allow you to define a concrete implementation that knows about your infrastructure services.

public class FooFactory : IFooFactory
{
    private readonly ISerializer serializer;
    private readonly IFileAccessHandler fileHandler;

    public FooFactory(ISerializer serializer, IFileAccessHandler fileHandler)
    {
        if(serializer == null)
        {
            throw new ArgumentNullException("serializer");
        }
        if(fileHandler == null)
        {
            throw new ArgumentNullException("fileHandler");
        }

        this.serializer = serializer;
        this.fileHandler = fileHandler;
    }

    public Foo Create(DomainClass dc)
    {
        return new Foo(this.serializer, this.fileHandler, dc);
    }
}

In this way you can protect the invariants of your Foo class, enabling you to stay with Constructor Injection.

In the DI container, you can register the IFooFactory and corresponding implementation. Everywhere you have a DomainClass instance and need a Foo instance, you would then take a dependency on IFooFactory and use that.

Leave a Comment