gpt4 book ai didi

c# - 动态注册泛型

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

我想使用 Unity 注册一个通用的 Repository 类。

这是我的通用类:

public class Repository<TModel> 
: IRepository<TModel> where TModel : class, IModel

TModel 是与 Entity 一起使用的 POCO 对象。

如果我这样注册它就可以了。

IOC_Container.RegisterType(typeof(IRepository<Employee>), typeof(Repository<Employee>));

这需要我注册每个 TModel,这会变得很麻烦。

我有一个使用反射动态注册我的服务类的 Bootstrap ,我想对存储库做同样的事情。

这是服务的 Bootstrap 代码:

var currentAssembly = Assembly.LoadFrom(assembly);
var assemblyTypes = currentAssembly.GetTypes();

foreach (var assemblyType in assemblyTypes)
{
if (assemblyType.IsInterface)
{
continue;
}

if (assemblyType.FullName.EndsWith("Service"))
{
foreach (var requiredInterface in assemblyType.GetInterfaces())
{
if (requiredInterface.FullName.EndsWith("Service"))
{
var typeFrom = assemblyType.GetInterface(requiredInterface.Name);
var typeTo = assemblyType;
IOC_Container.RegisterType(typeFrom, typeTo);
}
}
}
}

有什么建议吗?

最佳答案

Unity 3 支持 registration by convention .按照惯例使用注册,您的示例可能如下所示:

var currentAssembly = Assembly.LoadFrom(assembly);

IOC_Container.RegisterTypes(
currentAssembly.GetTypes().Where(
t => t.FullName.EndsWith("Service"),
WithMappings.MatchingInterface,
WithName.Default);

以上将注册一个IRepository<Employee>匹配接口(interface) Repository<Employee>具体类型。

这可以让注册多种类型时的生活更轻松一些,但对于您发布的特定存储库代码,您可能不需要该功能。 Unity 允许您注册开放的泛型类型,因此您可以只执行一个注册来代替注册 IRepository 的所有组合:

IOC_Container.RegisterType(
typeof(IRepository<>), typeof(Repository<>));

解析 IRepository<Employee> 时Unity 将使用 Employee 类型来解析 Repository<Employee> .

关于c# - 动态注册泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21056628/

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