如何使用unity根据注入的类型有条件地绑定实例? [英] How to conditionally bind a instance depending on the injected type using unity?

查看:152
本文介绍了如何使用unity根据注入的类型有条件地绑定实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于Ninject,对于一个特定的项目,我被要求学习Unity.

I'm used to Ninject, and for a specific project I'm asked to learn Unity.

有一件事我找不到有关该怎么做的信息.

There is one thing i can't find information on how to do.

我可以在Ninject中声明:

In Ninject I can state:

Bind<IWarrior>().To<Samurai>().Named("Samurai");
Bind<IWarrior>().To<Ninja>().Named("Ninja");
Bind<IWeapon>().To<Katana>().WhenInjectedInto(typeof(Samurai));
Bind<IWeapon>().To<Shuriken>().WhenInjectedInto(typeof(Ninja));

然后,当有人要一个叫武士的武士时,武士就带有卡纳纳(kanana),而忍者便是手里剑(shurikens).应当.

And then when one asks for the warrior named samurai, the samurai comes with kanana and the ninja comes with shurikens. As it should.

我不想引用战士中的容器来获得合适的武器,也不想使用属性污染模型(在另一个没有引用ninject或unity的程序集中)

I don't want to reference the container in the warriors to get the appropriate weapon, and don't want to contaminate the model with attributes (is in another assembly that doesn't have reference to ninject or unity)

PD:我正在寻找一种编码方式,而不是通过xml配置.

PD: I'm looking for a code way, not via xml config.

推荐答案

这应该适用于Unity:

This should work with Unity:

Container
 .Register<IWeapon, Katana>("Katana")
 .Register<IWeapon, Shuriken>("Shuriken")
 .Register<IWarrior, Samurai>("Samurai", new InjectionConstructor(new ResolvedParameter<IWeapon>("Katana"))
 .Register<IWarrior, Ninja>("Ninja", new InjectionConstructor(new ResolvedParameter<IWeapon>("Shuriken")));


测试:

var samurai = Container.Resolve<IWarrior>("Samurai");
Assert.IsTrue(samurai is Samurai);
Assert.IsTrue(samurai.Weapon is Katana);

var ninja = Container.Resolve<IWarrior>("Ninja");
Assert.IsTrue(ninja is Ninja);
Assert.IsTrue(ninja.Weapon is Shuriken);

这篇关于如何使用unity根据注入的类型有条件地绑定实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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