在安装依赖项时使用IoC容器是不好的做法或代码味道?

时间:2012-08-06 02:26:57

标签: c# inversion-of-control castle-windsor automapper

在安装依赖项时使用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个人档案的更好方法?

1 个答案:

答案 0 :(得分:0)

该方法唯一的错误是您手动指定IWindowsInstaller实现。使用反射来查找它们并使用Activator.CreateInstance来实例化实现。

它为您提供了一种灵活的配置方法,系统中的每个部件/模块都负责自己的注册。

但是我会为AutoMapper配置创建一个新界面IMapperConfiguration(单一责任)。使用反射也可以扫描组件。