gpt4 book ai didi

.net - Unity 2.0 通过 XML 注册泛型类型

转载 作者:行者123 更新时间:2023-12-04 02:54:21 25 4
gpt4 key购买 nike

我正在尝试在 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 类型语法。在其他任何地方,您都可以使用通用快捷语法。

关于.net - Unity 2.0 通过 XML 注册泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3486837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com