2016-06-27 208 views
10

我可以自動註冊實現接口這一說法解決依賴

IUnityContainer container = new UnityContainer(); 

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

我怎麼能指定接口和實現一個命名空間中的所有類型?

即:只有Framework.RepositoryInterfaces中的接口應根據Framework.RepositoryImplementations中的類型進行解析。

回答

9

可以使用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>(); 
2

嘗試過濾類型的命名空間

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>();