Castle Custom Lifestyle per Resolve

我怕爱的太早我们不能终老 提交于 2019-12-04 16:59:05

You must've heard people recommending to only call Resolve once for your app entry point (Main, Controller, etc.). Castle documentation has good guidelines on this.

Based on Mauricio's link, I got it working using factories:

public interface IComponentFactory
{
    T Get<T>();
}

var container = new WindsorContainer();
container.AddFacility<TypedFactoryFacility>();
container.Register(Component.For<LowLevelComponent>()
         .LifeStyle.Custom<ContextualLifestyle>());
container.Register(Component.For<HighLevelComponent>()
         .LifeStyle.Custom<ContextualLifestyle>());
container.Register(Component.For<IComponentFactory>().AsFactory());
//Register the "context-root" component in a child container
var subContainer = new WindsorContainer();
subContainer.Register(Component.For<ComponentBeingResolved>()
            .LifeStyle.Transient);
container.AddChildContainer(subContainer);
container.Register(
    Component.For<ComponentBeingResolved>()
        .LifeStyle.Transient
        //Here's the magic
        .UsingFactoryMethod(
            () =>
                {
                    using (new ContainerContext(container))
                        return subContainer.Resolve<ComponentBeingResolved>();
                }));

Usage:

var factory = container.Resolve<IComponentFactory>();
var instance1 = factory.Get<ComponentBeingResolved>();
var instance2 = factory.Get<ComponentBeingResolved>();

Not sure if this is a good hack or an ugly one, but it works wonderfully.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!