gpt4 book ai didi

c# - 当最大的构造函数具有无法解析的依赖项时,如何强制 Ninject 异常?

转载 作者:太空宇宙 更新时间:2023-11-03 10:29:25 25 4
gpt4 key购买 nike

根据 Ninject 的文档:

The primary DI pattern is Constructor Injection. When activating an instance of a type Ninject will choose one of the type’s constructors to use by applying the following rules in order:-

  1. If a constructor has an [Inject] attribute, it is used (but if you apply the attribute to more than one, Ninject will throw a NotSupportedException at runtime upon detection).

  2. If no constructors have an [Inject] attribute, Ninject will select the one with the most parameters that Ninject understands how to resolve.

  3. If no constructors are defined, Ninject will select the default parameterless constructor (assuming there is one).

如果您快速浏览此列表,似乎很难在 #2 中发现一个问题。难点在于 that Ninject understands how to resolve .

考虑以下场景:

// Defined in MyController.cs
public void MyController(IMyDependency depencency) { }

// Defined in MyController.generated.cs for T4
public void MyController() { }

如果 Ninject 没有任何类型绑定(bind)到 IMyDependency然后你调用kernel.Resolve<MyController>() ,它将不是异常,而是使用无参数构造函数传递。

但是,这绝对不是所需的行为,因为我想立即收到解析失败的通知,并且默认的 Ninject 功能也使得无法在编码测试中测试 IOC 解析。

如果在具有最多参数的构造函数上解析失败并且尽可能不回退到其他构造函数,是否有任何方法可以使 Ninject 异常?

最佳答案

实现您自己的 IConstructorScorer,可能通过子类化默认的 StandardConstructorScorer 并为您不喜欢其外观的构造函数提供低分...

Ninject runs each constructor through the IConstructorScorer interface to determine which constructor it should use to instantiate the class

有关如何执行此操作的详细信息,请参阅 documentation on github .

在您的情况下,它可能看起来像这样:

public class MyScorer : StandardConstructorScorer
{
public override int Score(IContext context, ConstructorInjectionDirective directive)
{
//has more than one constructor
//and the constructor being considered is parameterless
if (directive.Constructor.GetType().GetConstructors().Count() > 1
&& !directive.Targets.Any())
{
//give it a low score
return Int32.MinValue;
}
return base.Score(context, directive);
}
}

关于c# - 当最大的构造函数具有无法解析的依赖项时,如何强制 Ninject 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30744116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com