每次使用unity解析类型时注入新的构造方法参数 [英] Injecting new constructor parameters every time a type is resolved using unity
问题描述
我最近遇到了一个问题,我希望每次解决时都将新类型注入到请求的类型中.
I've just come across an issue recently where I want new types injected into the requested type every time it is resolved.
我要注册类型的当前代码是
The current code I have to register the type is
container.RegisterType<IFirstT, FirstT>();
container.RegisterType<ISecondT, SecondT>();
container.RegisterType<IInjectableT, InjectableT>()
.Configure<InjectedMembers>()
.ConfigureInjectionFor<InjectableT>(
new InjectionConstructor(
container.Resolve<IFirstT>(),
container.Resolve<ISecondT>(),
)
);
我现在意识到,每次我解析 IInjectableT 时,都会使用相同的注入构造函数.
I've now come to realise that the same injection constructor is being used every time I resolve the IInjectableT.
InjectionConstructor是否有可能每次都统一创建新的依赖项?
Is it possible that the InjectionConstructor will create new Dependencies everytime with unity?
我意识到我可以解决 InjectableT 的构造函数中的依赖关系并实现相同的功能,但是我打算让IOC控制这种行为并选择是否有新实例应该被注入或现有的传递给它.
I realise that I can just resolve the dependencies inside of the constructor of InjectableT and achieve the same thing, however I was intending for the IOC to controll this type of behaviour and choose if a new instance should be injected or an existing one passed to it.
推荐答案
您应使用ResolvedParameter:
You should use ResolvedParameter:
container.RegisterType<IInjectableT, InjectableT>(
new InjectionConstructor(
new ResolvedParameter<IFirstT>(),
new ResolvedParameter<ISecondT>()
)
);
这篇关于每次使用unity解析类型时注入新的构造方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!