Injecting new constructor parameters every time a

2019-09-17 04:49发布

问题:

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