使用多个构造函数注入类 [英] Injection of class with multiple constructors

查看:130
本文介绍了使用多个构造函数注入类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用NInject解决具有多个构造函数的类似乎无效.

Resolving a class that has multiple constructors with NInject doesn't seem to work.

public class Class1 : IClass
{
public Class1(int param) {...}
public Class1(int param2, string param3) { .. }
}

以下内容似乎无效:

IClass1 instance =
    IocContainer.Get<IClass>(With.Parameters.ConstructorArgument("param", 1));

模块中的钩子很简单,并且可以在添加额外的构造函数之前起作用: Bind().To();

The hook in the module is simple, and worked before I added the extra constructor: Bind().To();

推荐答案

不起作用的原因是,在.ctor选择过程中未考虑手动提供的.ctor参数. .ctors根据它们具有多少个参数(在参数类型上有绑定)而被计分.在激活期间,将应用手动提供的.ctor参数.由于您没有对int或string的绑定,因此不会对它们进行评分.您可以通过将[Inject]属性添加到要使用的.ctor来强制评分.

The reason that it doesn't work is that manually supplied .ctor arguments are not considered in the .ctor selection process. The .ctors are scored according to how many parameters they have of which there is a binding on the parameter type. During activation, the manually supplied .ctor arguments are applied. Since you don't have bindings on int or string, they are not scored. You can force a scoring by adding the [Inject] attribute to the .ctor you wish to use.

这篇关于使用多个构造函数注入类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆