我可以自动注册实现与此语句接口的所有类型
IUnityContainer container = new UnityContainer(); container.RegisterTypes( AllClasses.FromAssembliesInBasePath(),WithMappings.FromMatchingInterface,WithName.Default,WithLifetime.Transient); ICustomer result = container.Resolve<ICustomer>();
如何为接口和实现指定命名空间?
即:Framework.RepositoryInterfaces中的接口只能通过Framework.RepositoryImplementations中的类型解析.
解决方法
您可以使用
RegistrationConvention:
public class NamespaceRegistrationConvention : RegistrationConvention { private readonly IEnumerable<Type> _typestoResolve; private readonly string _namespacePrefixForInterfaces; private readonly string _namespacePrefixForImplementations; public NamespaceRegistrationConvention(IEnumerable<Type> typestoResolve,string namespacePrefixForInterfaces,string namespacePrefixForImplementations) { _typestoResolve = typestoResolve; _namespacePrefixForInterfaces = namespacePrefixForInterfaces; _namespacePrefixForImplementations = namespacePrefixForImplementations; } public override IEnumerable<Type> GetTypes() { // Added the abstract as well. You can filter only interfaces if you wish. return _typestoResolve.Where(t => ((t.IsInterface || t.IsAbstract) && t.Namespace.StartsWith(_namespacePrefixForInterfaces)) || (!t.IsInterface && !t.IsAbstract && t.Namespace.StartsWith(_namespacePrefixForImplementations))); } public override Func<Type,IEnumerable<Type>> GetFromTypes() { return WithMappings.FromMatchingInterface; } public override Func<Type,string> GetName() { return WithName.Default; } public override Func<Type,LifetimeManager> GetLifetimeManager() { return WithLifetime.Transient; } public override Func<Type,IEnumerable<InjectionMember>> GetInjectionMembers() { return null; } }
并通过以下方式使用:
container.RegisterTypes(new NamespaceRegistrationConvention(AllClasses.FromAssembliesInBasePath(),"Framework.RepositoryInterfaces","Framework.RepositoryImplementations"); ICustomer result = container.Resolve<ICustomer>();
原文地址:https://www.jb51.cc/csharp/95095.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。