是否可以使用 Ninject,在实例化新的 class 时省略参数?

Is it possible, using Ninject, to omit parameters when instantiating a new class?

要使用 Ninject 我可以做类似下面的事情

var kernal = new StandardKernel();
kernal.Load(Assembly.GetExecutingAssembly());
var thing = new ThingThatNeedsAWarrior(kernal.Get<IWarrior>());

但是在实例化新的 class 时是否可以使用 Ninject 省略参数?

var thing = new ThingThatNeedsAWarrior();

当构造函数签名为

public ThingThatNeedsAWarrior(IWarrior warrior)

ninject对new没有影响。这个想法是你的内核来实例化东西,就像这样:

var thing = kernel.Get<ThingThatNeedsAWarrior>();

那么你不需要指定参数。 Ninject 将选择它知道如何解析的参数最多的构造函数。

更进一步,理想情况下,在应用程序中配置内核,然后执行如下操作:

var applicationRoot = kernel.Get<ApplicationRoot>();

并一次性实例化应用程序的所有对象(作为 ApplicationRoot 的依赖项)。

Mark Seeman 也有一篇博客 post 关于 where/how 配置 DI:CompositionRoot。他还对 DI 容器的使用有了更多了解。

(感谢@NighOwl888 指正)