2016-06-27 18 views
10

tôi có thể tự động đăng ký tất cả các loại mà thực hiện giao diện với tuyên bố nàyphụ thuộc Resolve chỉ từ namespace định

IUnityContainer container = new UnityContainer(); 

container.RegisterTypes(
    AllClasses.FromAssembliesInBasePath(), 
    WithMappings.FromMatchingInterface, 
    WithName.Default, 
    WithLifetime.Transient); 
ICustomer result = container.Resolve<ICustomer>(); 

Làm thế nào tôi có thể xác định một không gian tên cho các giao diện và hiện thực?

tức là: chỉ các giao diện trong Framework.RepositoryInterfaces mới được giải quyết theo loại trong Framework.RepositoryImplementations.

Trả lời

9

Bạn có thể sử dụng 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; 
    } 
} 

Và sử dụng nó thông qua:

container.RegisterTypes(new NamespaceRegistrationConvention(AllClasses.FromAssembliesInBasePath(), "Framework.RepositoryInterfaces", "Framework.RepositoryImplementations"); 
ICustomer result = container.Resolve<ICustomer>(); 
2

loại lọc Thử bởi namespace

IUnityContainer container = new UnityContainer(); 

container.RegisterTypes(
    AllClasses.FromAssembliesInBasePath().Where(
    t => t.Namespace.StartsWith("Framework.RepositoryImplementations") || 
    t.Namespace.StartsWith("Framework.RepositoryInterfaces")), 
    WithMappings.FromMatchingInterface, 
    WithName.Default, 
    WithLifetime.Transient); 

ICustomer result = container.Resolve<ICustomer>(); 
Các vấn đề liên quan