1

How to inject only one object to constructor using Unity DI. Example:

public class MyClass{

public MyClass(ILog logger, IProvider provider, IResolver resolver, ItemTypeEnum itemType)
{
   //.... initializing everything
}

public ItemTypeEnum ItemType { get; set;}

//....methods where I will use this itemKind
}

I want to inject only itemType value to the constructor, to use this itemType in implementation depends of value of this enum.

Tomasz M
  • 53
  • 8
  • I have to ask, why would you want to only inject one of those dependencies? – Crowcoder Feb 07 '18 at 16:27
  • If you have to ask this question, it is a sign that `MyClass` is doing more than one responsibility, and is therefore a violation of the Single Responsibility Principal. – NightOwl888 Feb 07 '18 at 20:42

2 Answers2

0

Disclaimer: I might have gotten the question wrong, but to me it only makes sense to inject all dependencies but itemType, not the other way round.

The easiest option is to create a MyClassFactory with a CreateMyClass( ItemTypeEnum itemType ) method. Details see over there...

Haukinger
  • 10,420
  • 2
  • 15
  • 28
0

You can use InjectionConstructor and provide parameter during the resolution. The example is as following:

container.RegisterType<ILog, Log>();
container.RegisterType<IResolver, Resolver>();
container.RegisterType<IProvider, Provider>();
container.RegisterType<MyClass>(new InjectionConstructor(
    new ResolvedParameter<ILog>(),
    new ResolvedParameter<IProvider>(),
    new ResolvedParameter<IResolver>(),
    typeof(ItemTypeEnum)));                

MyClass mc = container.Resolve<MyClass>(new ParameterOverride("itemType", ItemTypeEnum.Value));
Johnny
  • 8,939
  • 2
  • 28
  • 33