问题描述
我有一个接口:IFoo
实现该接口的两个类:FooOne
和FooTwo
并且两个类ClassOne
和ClassTwo
在构造函数中接收一个IFoo
参数.
I have one interface: IFoo
Two classes implementing that interface: FooOne
and FooTwo
And two classes ClassOne
and ClassTwo
receiving an IFoo
parameter in the constructor.
如何配置统一性,以便ClassOne
仅使用一个容器接收FooOne
实例,而ClassTwo
接收FooTwo
?
How I configure unity so ClassOne
receives a FooOne
instance and ClassTwo
receives a FooTwo
using only one container?
我无法在运行时执行此操作,因此它必须位于配置文件中.
I can't do it at runtime so it must be in the config file.
推荐答案
看看统一文档.
对于更具可读性的配置文件,您应该为IFoo
,FooOne
,FooTwo
,ClassOne
和ClassTwo
定义类型别名.然后,您需要注册从IFoo
到实现的映射.您需要为映射设置name
.对于IFoo
的使用者,您需要注册InjectionConstructor
.
For a more readable config file you should define type aliases for IFoo
, FooOne
, FooTwo
, ClassOne
and ClassTwo
. Then you need to register the mappings from IFoo
to your implementations. You need to set a name
for the mappings.For the consumers of IFoo
you need to register an InjectionConstructor
.
您的配置将如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="IFoo" type="UnityConfigFile.IFoo, UnityConfigFile" />
<alias alias="FooOne" type="UnityConfigFile.FooOne, UnityConfigFile" />
<alias alias="FooTwo" type="UnityConfigFile.FooTwo, UnityConfigFile" />
<alias alias="ClassOne" type="UnityConfigFile.ClassOne, UnityConfigFile" />
<alias alias="ClassTwo" type="UnityConfigFile.ClassTwo, UnityConfigFile" />
<container>
<register type="IFoo" name="1" mapTo="FooOne" />
<register type="IFoo" name="2" mapTo="FooTwo" />
<register type="ClassOne" mapTo="ClassOne">
<constructor>
<param name="foo">
<dependency type="IFoo" name="1" />
</param>
</constructor>
</register>
<register type="ClassTwo" mapTo="ClassTwo">
<constructor>
<param name="foo">
<dependency type="IFoo" name="2" />
</param>
</constructor>
</register>
</container>
</unity>
</configuration>
这是显示其工作方式的相应测试.
That's the corresponding test that shows how it works.
UnityConfigurationSection config =
(UnityConfigurationSection) ConfigurationManager.GetSection("unity");
IUnityContainer container = new UnityContainer();
container.LoadConfiguration(config);
ClassTwo two = container.Resolve<ClassTwo>();
Assert.IsInstanceOfType(two.Foo, typeof(FooTwo));
更新
在运行时,您可以这样做
At runtime you can do it like this
IUnityContainer container = new UnityContainer();
container.RegisterType<IFoo, FooOne>("One");
container.RegisterType<IFoo, FooTwo>("Two");
container.RegisterType<ClassOne>(new InjectionConstructor(
new ResolvedParameter<IFoo>("One")));
container.RegisterType<ClassTwo>(new InjectionConstructor(
new ResolvedParameter<IFoo>("Two")));
这篇关于Unity-为同一接口注入不同的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!