c# – 仅从指定的命名空间解析依赖关系
发布时间:2020-12-15 06:36:57 所属栏目:百科 来源:网络整理
导读:我可以自动注册实现与此语句接口的所有类型 IUnityContainer container = new UnityContainer();container.RegisterTypes( AllClasses.FromAssembliesInBasePath(),WithMappings.FromMatchingInterface,WithName.Default,WithLifetime.Transient);ICustomer
|
我可以自动注册实现与此语句接口的所有类型
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>(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
