开发者

Castle.Windsor per request lifestyle: subcontainers vs custom lifestyle

开发者 https://www.devze.com 2023-04-02 10:16 出处:网络
I need a per request lifestyle in Castle.Windsor. This is not an ASP app, and the native PerWebRequest lifestyle will not work.

I need a per request lifestyle in Castle.Windsor. This is not an ASP app, and the native PerWebRequest lifestyle will not work.

Before processing a request I do (for every request):

MyContainer = new Container();
MyContainer.Register(
    Component.For<ICache>().ImplementedBy<Cache>().LifeStyle.Singleton
    );
MyMainStaticContainer.AddChildContainer(MyContainer);
//MyMainStaticCo开发者_运维百科ntainer contains implementations which
//can be shared across requests

Then somewhere in the code:

MyContainer.Resolve<ICache>().Items.Add("x", "y");
...
MyContainer.Resolve<ICache>().Items.Get("x");

Finally, when the work is done (in ASP it would be in Application_EndRequest)

MyContainer.Parent.RemoveChildContainer(MyContainer);
MyContainer.Dispose();

This is quite elegant (as in: not a lot of steps, simple to understand) and it works for me, but I am quite curious if implementing a custom lifestyle would be better (safer?, more efficient?).

Thanks in advance,

Tymek


Have you tried "Transient"?

This link may help you pick the right one for your needs: CastleProject - Lifestyles

NOTE: To save you from registering this on every request, you may want to take advantage of the IDs in the Windsor.config. IDs will allow you to have multiple implementations of ICache and you can pull them out of Windsor using the Interface-ID composite key.

in Windsor.config:

<component id="MyDefaultCache"
           service="MyAssembly.ICache, MyAssembly"
           type="MyAssembly.MyDefaultCache, MyAssembly" />
<component id="MySpecialCache" 
           service="MyAssembly.ICache, MySpecialCache"
           type="MySpecialAssembly.MySpecialCache, MySpecialAssembly" />

and in code:

MyContainer.Resolve<ICache>("MySpecialCache")

The first one is always default, so MyContainer.Resolve<ICache> will resolve to MyAssembly.MyDefaultCache

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号