开发者

Is it possible to change configured lifetime manager when resolving type?

开发者 https://www.devze.com 2023-02-09 10:40 出处:网络
I have my Unity configured to be able to resolve several types with my own lifetime manager (per http request). Now in one special initialization method I need to get fresh instances of resolved types

I have my Unity configured to be able to resolve several types with my own lifetime manager (per http request). Now in one special initialization method I need to get fresh instances of resolved types structure and I don't want these instances to be stored and reused for subsequent Resolve calls = for this special method I need transient lifetime manager.

I want to avoid second container configuration because it will be copy of the first one with different lifetime managers. Is it possible somehow override lifetime manager configuration when resolving the type?

This question is realted to my previous question because I'm looking for better way to do that.

Edit:

I know that I can create multiple named registrations but that whould require creating big part of co开发者_开发技巧nfiguration again just because of changing lifetime manager.


You could use a child container for the special resolve. Just register a new lifetime manager (TransientLifetimeManager sounds like what you want) in the child container for the types you care about. It'll take the registrations from the parent for everything else, so you don't need to redo massive chunks of registration.

But I agree with Aliostad - this design smells wrong, but without more details of what you're doing I can't really suggest an alternative.


I think - as you have noted - we can use two separate registrations with tow different lifetime configurations. But you seem not to be happy with this setup and you would like to pass the lifetime at the time of registration.

My suggestion is to create an extension method which takes an additional lifetime and checks the container for such registration and if it does not exist, it registers it and returns with the setup you require.

But to be honest, I do have a problem with this approach, even if such a method existed in the framework. IoC containers remove the knowledge of the dependant on the dependency but you are adding this knowledge back to the client/dependant which against the IoC principle.

0

精彩评论

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

关注公众号