我想使用Unity注册一个通用的Repository类。
这是我的泛型类:
public class Repository<TModel>
: IRepository<TModel> where TModel : class, IModelTModel是与Entity一起使用的POCO对象。
如果我像这样注册它,它就能工作。
IOC_Container.RegisterType(typeof(IRepository<Employee>), typeof(Repository<Employee>));不过,这需要我注册每个TModel,这会变得很麻烦。
我有一个引导程序,它使用反射动态注册我的服务类,我想对存储库做同样的事情。
以下是服务的引导程序代码:
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);
}
}
}
}}
有什么建议吗?
发布于 2014-01-14 04:01:37
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);上面的代码将为匹配的Repository<Employee>具体类型注册一个IRepository<Employee>接口。
当注册多个类型时,这可以使工作变得更容易,但对于您发布的特定存储库代码,您可能不需要该功能。Unity允许您注册开放泛型类型,因此您可以只执行一次注册,而不是注册IRepository的所有组合:
IOC_Container.RegisterType(
typeof(IRepository<>), typeof(Repository<>));https://stackoverflow.com/questions/21056628
复制相似问题