Ninject传入构造函数值 [英] Ninject passing in constructor values

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

问题描述

使用Ninject,你怎么配置内核,所以我可以定义构造函数的值传递到对象的实例呢?

With Ninject, how do you configure the kernel so I can define what constructor values are passing into the instantiation of an object?

我在一个模块进行以下配置:

I have the following configured in a module:

Bind<IService1>()
    .To<Service1Impl>()
    .InSingletonScope()
    .Named("LIVE");
Bind<IService2>()
    .To<Service2Impl>()
    .InSingletonScope()
    .Named("LIVE")
    .WithConstructorArgument(
        "service1", 
        Kernel.Get<IService1>("LIVE"));

Service2Impl需要IService1的构造函数的参数,但是我想这来自于容器中。我也希望有我的code将在运行时针对不同的版本命名的绑定。

Service2Impl takes a constructor parameter of IService1 but I want this to come from the container. I also want to have named bindings as my code will be targeting different versions at runtime.

这似乎工作,但它是正确的方式来达到我想要做什么? 我应该实现不使用命名绑定和接线不同的配置模块到内核?

This seems to work but is it the right way to achieve what I want to do? Should I be achieving without the use of named bindings and wiring different configuration modules into the kernel?

修改

我已经使用了ToMethod()方法就是指定一个委托,对特定类型的请求调用。这似乎有点更好,我会得到编译时警告,如果构造的配置是错误的,而不必知道我是第一个传递的参数的名称。

I have used the ToMethod() method now to specify a delegate to call on request of a specific type. This seems a bit nicer as I'll get compile time warnings if the constructor configuration is wrong rather than having to know the name of the parameter I am passing first.

感谢

推荐答案

我到底该用ToMethod,这让我来构造,以保持编译时错误与构造所需的实例。

I used ToMethod in the end, which allowed me to construct the required instance with constructors in order to maintain compile time errors.

例如:

.ToMethod(Func<IContext, T> method)

Bind<IWeapon>().ToMethod(context => new Sword());

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

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