注入具有多个构造函数的类

发布于 2024-08-26 15:03:04 字数 374 浏览 5 评论 0原文

使用 NInject 解析具有多个构造函数的类似乎不起作用。

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

以下似乎不起作用:

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

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

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) { .. }
}

the following doesn’t seem to work:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月无声 2024-09-02 15:03:05

它不起作用的原因是在 .ctor 选择过程中不考虑手动提供的 .ctor 参数。 .ctor 根据其具有参数类型绑定的参数数量进行评分。在激活期间,将应用手动提供的 .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.

本王不退位尔等都是臣 2024-09-02 15:03:05

您遇到的问题是 Ninject 根据可用的绑定参数数量选择 .ctors。这意味着 Ninject 从根本上不理解重载。

您可以通过在绑定中使用 .ToConstructor() 函数并将其与 .Named() 函数结合起来解决此问题。这使您可以为同一个类创建多个绑定到具有不同名称的不同构造函数。这有点笨拙,但很有效。

我维护着自己的软件开发博客,所以这最终成为了一篇关于它的文章。如果您想要一些示例代码和更多解释,您应该查看一下。

http://www.nephandus.com/2013/05/10/overloading-忍者/

The problem you're having is that Ninject selects .ctors based on the number of bound parameters available to it. That means that Ninject fundamentally doesn't understand overloading.

You can work around this problem by using the .ToConstructor() function in your bindings and combining it with the .Named() function. That lets you create multiple bindings for the same class to different constructors with different names. It's a little kludgy, but it works.

I maintain my own software development blog so this ended up being a post on it. If you want some example code and a little more explanation you should check it out.

http://www.nephandus.com/2013/05/10/overloading-ninject/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文