我想使用Unity注册一个通用的Repository类.
这是我的通用类:
public class Repository: IRepository where TModel : class, IModel
TModel是与Entity一起使用的POCO对象.
如果我这样注册就行了.
IOC_Container.RegisterType(typeof(IRepository), typeof(Repository ));
这需要我注册每个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); } } } }
}
有什么建议?
Unity 3支持按惯例注册.按惯例使用注册,您的示例可能如下所示:
var currentAssembly = Assembly.LoadFrom(assembly);
IOC_Container.RegisterTypes(
currentAssembly.GetTypes().Where(
t => t.FullName.EndsWith("Service"),
WithMappings.MatchingInterface,
WithName.Default);
以上将注册IRepository<Employee>
一个匹配的Repository<Employee>
具体类型的接口.
注册多种类型时,这可以使生活更轻松,但对于您发布的特定存储库代码,您可能不需要该功能.Unity允许您注册开放的泛型类型,以便代替注册IRepository的所有组合,您只需执行一次注册:
IOC_Container.RegisterType(
typeof(IRepository<>), typeof(Repository<>));
解析IRepository<Employee>
Unity时将使用Employee类型来解析Repository<Employee>
.