Injecting new constructor parameters every time a type is resolved using unity

不打扰是莪最后的温柔 提交于 2020-01-17 06:58:28

问题


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>(),
           )
    );

I've now come to realise that the same injection constructor is being used every time I resolve the IInjectableT.

Is it possible that the InjectionConstructor will create new Dependencies everytime with unity?

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.


回答1:


You should use ResolvedParameter:

container.RegisterType<IInjectableT, InjectableT>(
          new InjectionConstructor(
                  new ResolvedParameter<IFirstT>(),
                  new ResolvedParameter<ISecondT>()
           )
    );


来源:https://stackoverflow.com/questions/5188335/injecting-new-constructor-parameters-every-time-a-type-is-resolved-using-unity

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