当使用代码在Unity Container中注册和解析类型时,您可以使用“注册名称”来消除从接口或基类层次结构派生的引用的歧义。
“注册名称”文本将作为注册和解析方法的参数提供:
myContainer.RegisterType<IMyService, CustomerService>("Customers");和
MyServiceBase result = myContainer.Resolve<MyServiceBase>("Customers");但是,当我在配置文件中注册类型时,我看不到“注册名称”可以被分配到哪里
我注册了一个接口:
<typeAlias alias="IEnlistmentNotification" type="System.Transactions.IEnlistmentNotification, System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />然后我碰巧知道有两种类型实现了这个接口:
<typeAlias alias="PlaylistManager" type="Sample.Dailies.Grid.Workers.PlaylistManager, Sample.Dailies.Grid.Workers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<typeAlias alias="FlexAleManager" type="Sample.Dailies.Grid.Workers.FlexAleManager, Sample.Dailies.Grid.Workers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />然后我提供了接口和这两种类型之间的映射:
<type type="IEnlistmentNotification" mapTo="FlexAleManager"><lifetime type="singleton"/></type>
<type type="IEnlistmentNotification" mapTo="PlaylistManager"><lifetime type="singleton"/></type>这似乎与下面的代码相对应:
myContainer.RegisterType<IEnlistmentNotification, FlexAleManager>();
myContainer.RegisterType<IEnlistmentNotification, PlaylistManager>();但很明显,我需要的是一个与以下代码相对应的消歧配置项:
myContainer.RegisterType<IEnlistmentNotification, FlexAleManager>("Flex");
myContainer.RegisterType<IEnlistmentNotification, PlaylistManager>("Play");然后,当我进入我的代码时,我可以这样做:
IEnlistmentNotification flex = myContainer.Resolve<IEnlistmentNotification>("Flex");
IEnlistmentNotification play = myContainer.Resolve<IEnlistmentNotification>("Play");懂得我的意思吗?
谢谢,
金鲍尔
发布于 2009-06-30 01:48:44
为了回答我自己的问题,我在Codeplex/Unity主页上找到了这个残片:
<type type="IFoo" mapTo="ServerFoo" name="server" />
<type type="IFoo" mapTo="ClientFoo" name="client">
<typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,Microsoft.Practices.Unity.Configuration">
<constructor>
<param name="server" parameterType="IFoo">
<dependency name="server" />
</param>
</constructor>
</typeConfig></type>请注意,type元素有一个额外的字段:'name‘,这是我不知道的。这提供了我正在寻找的“注册名称”值。
此外,param元素还有一个名为dependency的子元素,它具有一个执行相同功能的name属性。
所以..。感谢codeplex!
金鲍尔
https://stackoverflow.com/questions/1061051
复制相似问题