1

在使用代码在 Unity 容器中注册和解析类型时,您可以使用“注册名称”来消除源自接口或基类层次结构的引用的歧义。

'registration name' 文本将作为参数提供给 register 和 resolve 方法:

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");

明白了吗?

谢谢,

金博尔

4

1 回答 1

1

to answer my own question, I found this scrap on Codeplex/Unity home:

<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>

Notice that the type element has an additional field: 'name' that I was unaware of. This provides the 'registration name' value I was looking for.

Also the param element also has a subelement named dependency with a name attribute that performs the same function.

So... Thanks to codeplex!

Kimball

于 2009-06-30T01:48:43.987 回答