简体   繁体   中英

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;
}

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 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM