简体   繁体   English

如何使用统一DI仅将一个对象注入构造函数

[英]How to inject only one object to constructor using unity DI

How to inject only one object to constructor using Unity DI. 如何使用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. 我只想将itemType值注入构造函数,以便在实现中使用此itemType取决于此枚举的值。

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. 免责声明:我可能把这个问题弄错了,但是对我来说,注入所有依赖itemType除了 itemType是有意义的,而不是相反。

The easiest option is to create a MyClassFactory with a CreateMyClass( ItemTypeEnum itemType ) method. 最简单的选择是使用CreateMyClass( ItemTypeEnum itemType )方法创建MyClassFactory Details see over there ... 详细信息在那边 ...

You can use InjectionConstructor and provide parameter during the resolution. 您可以使用InjectionConstructor并在解析过程中提供参数。 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM