Ninject - 初始化对象

发布于 2024-08-26 20:37:35 字数 272 浏览 3 评论 0原文

我是 ninject 的新手,我想知道如何在构造注入对象时运行自定义初始化代码? IE。我有一个实现 IWeapon 的 Sword 类,但我想将生命值传递给 Sword 类构造函数,如何实现?我需要编写自己的提供程序吗?

一个小问题, IKernel kernel = new StandardKernel(new Module1(), new Module2(), ...);内核中拥有多个模块的实际用途是什么?我有点理解它,但有人能给我一个正式的解释和用例吗?

多谢!

詹姆斯

I am new to ninject, I am wondering how I can run custom initizlisation code when constructing the injected objects? ie. I have a Sword class which implements IWeapon, but I want to pass an hit point value to the Sword class constructor, how do I achieve that? Do I need to write my own provider?

A minor question, IKernel kernel = new StandardKernel(new Module1(), new Module2(), ...); what is the actual use of having multiple modules in Kernel? I sorta understand it, but could someone give me a formal explaination and use case?

Thanks a lot!

James

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

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

发布评论

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

评论(1

漫漫岁月 2024-09-02 20:37:35

如果您有一个具有以下构造函数的 Sword 类:

public Sword(int hitPoints)
    ...

您可能更喜欢像这样实例化 Swords,而不是实现 Provider:

IWeapon sword1 = kernel.Get<IWeapon>(With.Parameters.ConstructorArgument("hitPoints", 10));
IWeapon sword2 = kernel.Get<IWeapon>(With.Parameters.ConstructorArgument("hitPoints", 20));

If you have a class Sword with this constructor:

public Sword(int hitPoints)
    ...

Rather than implementing a Provider, you may prefer to instantiate Swords like this:

IWeapon sword1 = kernel.Get<IWeapon>(With.Parameters.ConstructorArgument("hitPoints", 10));
IWeapon sword2 = kernel.Get<IWeapon>(With.Parameters.ConstructorArgument("hitPoints", 20));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文