2012-08-06 57 views
5

安裝依賴關係時使用IoC容器是不好的做法還是代碼味道?安裝依賴關係時使用IoC容器是不好的做法還是代碼味道?

這是我的作文根:

public void Install(IWindsorContainer container, IConfigurationStore store) 
{ 
    Assembly modelAssembly = typeof(UserLoginModel).Assembly; 
    Assembly controllerAssembly = typeof(HomeController).Assembly; 

    container.Install(
     new MvcInfrastructureInstaller(modelAssembly, viewAssembly, controllerAssembly, applicationTitle, resourceAssemblyLocations), 
     new MiniMembershipInstaller(), 
     new ServiceInstaller(), 
     new RepositoryInstaller(), 
     new LibraryInstaller(), 
     new AutoMapperProfileInstaller() // this installer needs to resolve dependencies such as repositories through the container itself, so it goes last. 
    ); 
} 

AutoMapperProfileInstaller需要解決其中包含以初始化映射

public class AutoMapperProfileInstaller : IWindsorInstaller 
{ 
    public void Install(IWindsorContainer container, IConfigurationStore store) 
    { 
     Profile entityToViewModel = container.Resolve<EntityToViewModelProfile>(); 
     Profile[] profiles = new[] { entityToViewModel }; 

     Mapper.Initialize(config => 
     { 
      config.ConstructServicesUsing(container.Resolve); 

      foreach (Profile profile in profiles) 
      { 
       config.AddProfile(profile); 
      } 
     }); 
    } 
} 

這感覺錯在許多層面上的依賴關係的輪廓,這將是一個更好的方式來初始化配置文件AutoMapper

回答

0

該方法唯一的問題是您手動指定IWindowsInstaller實現。使用反射來查找它們並且Activator.CreateInstance來實例化實現。

它爲您提供了一個靈活的配置方法,其中系統中的每個部件/模塊負責其自己的註冊。

但是,我會爲AutoMapper配置IMapperConfiguration(Single Responsibility)創建一個新接口。使用反射也可以掃描這些程序集。

相關問題