问题描述
我意识到构造函数注入是首选,但我很好奇,如何使用注入的另一种形式时使用Ninject的语境命名绑定。
具体怎么办使用DependencyResolver或财产注射时以下。
公共则将MyService([命名(阿尔法)] IRepository库)
{
this.repository =库;
}
您可以创建一个名为结合在阿尔法工作:
绑定< IRepository>()为< AlphaRepository>()命名(阿尔法);
然后就可以指定其他人一样:
绑定< IRepository方式>()为< AnotherRepository方式>()命名(测试版);
当你的例子构造函数用于你会得到AlphaRepository。
为了使用的名称与属性赋予一个名字属性,就像你的财产你做的参数:
[注入,命名(阿尔法)]
公共IRepository美孚{搞定;设置;}
I realize constructor injection is preferred but I'm curious how to use Ninject's contextual 'Named Bindings' when using another form of injection.
Specifically how do I do the following when using DependencyResolver or property injection.
public MyService([Named("Alpha")] IRepository repository)
{
this.repository = repository;
}
You can create a named binding to work on Alpha:
Bind<IRepository>().To<AlphaRepository>().Named("Alpha");
then you can specify others like:
Bind<IRepository>().To<AnotherRepository>().Named("Beta");
When your example constructor is used you will get the AlphaRepository.
In order to use the name with a property give the property a name attribute just like you you did for the param:
[Inject, Named("Alpha")]
public IRepository Foo {get; set;}
这篇关于如何使用Ninject命名绑定随着DependencyResolver和PropertyInjection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!