.net – Unity 2.0通过XML注册通用类型

我正在尝试在Unity 2.0的配置文件注册通用类型,但似乎无法正确.我一直在这里提到MS文档: http://msdn.microsoft.com/en-us/library/ff660933%28v=PandP.20%29.aspx#_Generic_Types

代码如下所示:

public interface IRepository<T> where T : class
{
    ...
}

public class GenericRepository<T> : IRepository<T> where T : class
{
    ...
}

public class BlogRepository : GenericRepository<BlogRepository>
{
    ...
}

我现在拥有的XML配置如下:

<unity>
    <!-- Aliases -->
    <alias alias="BlogIRepository" 
           type="X.Services.Interfaces.IRepository[[X.Domain.Entities.Blog,X.Domain]],X.Services"/>

    <alias alias="BlogRepository" 
           type="X.Repositories.BlogRepository,X.Repositories"/>

    <!-- Type registration -->
    <container name="development">
        <!-- Common connection string value -->
        <instance name="Conn" type="System.String" value="blahblahblah"/>
        <register type="BlogIRepository" mapTo="BlogRepository">
            <constructor>
                <param name="connectionString" type="System.String" dependencyName="Conn"/>
            </constructor>
        </register>
    </container>
</unity>

根据注册通用类型的文档,您可以在通用类型周围使用方括号,如果类型不是系统类型,则在更多方括号内提供完全限定类型.我认为这是我做的.然而 – 没有工作.

编辑:MSDN站点示例:

<register type="IDictionary[string,[MyApp.Interfaces.ILogger,MyApp]]"/>

产生的错误是:

The type name or alias IRepository Could not be resolved. Please check your configuration file and verify this type name.

MSDN没有错.我们特别添加了一些快捷方式解析规则,以便您在大多数情况下不必输入所有的“和方括号”.

我一起拍了个样子,看起来大多像你的样子:

public interface IRepository<T> where T: class
{

}

public class GenericRepository<T> : IRepository<T> where T : class
{

}

public class BlogRepository : GenericRepository<Blog>
{

}

public class Blog
{

}

我的XML配置如下所示:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <namespace name="UnityConfigExample"/>
    <assembly name="UnityConfigExample"/>

    <container>
      <register type="IRepository[]" mapTo="GenericRepository[]" />
      <register type="IRepository[Blog]" mapTo="BlogRepository" />
    </container>
  </unity>

它只是工作.

你有没有尝试使用别名进行IRepository而不是命名空间/汇编搜索?我也使用别名进行以下工作:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <alias alias="IRepository" type="UnityConfigExample.IRepository`1,UnityConfigExample" />
    <alias alias="GenericRepository" type="UnityConfigExample.GenericRepository`1,UnityConfigExample"/>
    <alias alias="BlogRepository" type="UnityConfigExample.BlogRepository,UnityConfigExample"/>
    <alias alias="Blog" type="UnityConfigExample.BlogRepository,UnityConfigExample"/>

    <container>
      <register type="IRepository[]" mapTo="GenericRepository[]" />
      <register type="IRepository[Blog]" mapTo="BlogRepository" />
    </container>
  </unity>

当您指定别名的类型时,必须使用CLR类型语法.在其他地方,您可以使用通用快捷方式语法.

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念