Search code examples
c#asp.net.netsimple-injector

Factory facility in Simple Injector


I am migrating from Windsor to Simple Injector, I tried to follow the following this link. But I could not find any replacement for:

container.AddFacility<TypedFactoryFacility>();
container.Register(Component.For<ICacheDependencyFactory>().AsFactory());

What will be the replacement the above code in Simple Injector?

Edited:

ICacheDependencyFactory.cs

public interface ICacheDependencyFactory
{
    T Create<T>()
       where T : ICacheDependency;

    void Release<T>(T cacheDependency)
        where T : ICacheDependency;
}

Solution

  • Castle's factory facility is able to generate a proxy class based on the interface you supply. This proxy class will call back into the container to request the creation of a new instance of such type.

    Simple Injector lacks such feature. Simple Injector doesn't implement this, because:

    • The number of factories your application code needs, should be fairly limited (to just a couple at most). Well designed applications hardly need factories.
    • It's really easy to implement this with a hand-written factory.
    • Hand-written factories should be part of your composition root (where there already is a dependency on the container). This prevents application code from having to take a dependency on the container.

    Here's an example:

    private sealed class CacheDependencyFactory : ICacheDependencyFactory {
        public Container Container { get; set; }
        public T Create<T>() where T : ICacheDependency, class {
            return this.Container.GetInstance<T>();
        }
    }
    

    This factory can be registered as follows:

    container.RegisterSingle<ICacheDependencyFactory>(
        new CacheDependencyFactory { Container = container });