Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 动态注册泛型类型_C#_Unity Container - Fatal编程技术网

C# 动态注册泛型类型

C# 动态注册泛型类型,c#,unity-container,C#,Unity Container,我想使用Unity注册一个通用存储库类 这是我的通用类: public class Repository<TModel> : IRepository<TModel> where TModel : class, IModel } 有什么建议吗?Unity 3支持。使用“按约定注册”,您的示例可能如下所示: var currentsassembly=Assembly.LoadFrom(Assembly); IOC_Container.RegisterTypes(

我想使用Unity注册一个通用存储库类

这是我的通用类:

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

有什么建议吗?

Unity 3支持。使用“按约定注册”,您的示例可能如下所示:

var currentsassembly=Assembly.LoadFrom(Assembly);
IOC_Container.RegisterTypes(
currentAssembly.GetTypes()。其中(
t=>t.FullName.EndsWith(“服务”),
使用mappings.MatchingInterface,
WithName.Default);
上面将注册一个
i存储库
接口到匹配的
存储库
具体类型

这可以使注册多个类型时的工作更轻松,但对于您发布的特定存储库代码,您可能不需要该功能。Unity允许您注册打开的泛型类型,因此您可以只执行一次注册,而不必注册IRepository的所有组合:

IOC\u Container.RegisterType(
typeof(IRepository)、typeof(Repository));
解析
IRepository
时,Unity将使用类型Employee解析
存储库

IOC_Container.RegisterType(typeof(IRepository<Employee>), typeof(Repository<Employee>));
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);
            }
        }
    }
}