使用IoC容器来安装依赖项是一种不好的实践还是代码异味?

5
在安装依赖项时使用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
唯一的问题是您手动指定了 IWindowsInstaller 实现。使用反射来查找它们,并使用 Activator.CreateInstance 来实例化这些实现。
这样可以为您提供灵活的配置方法,使系统中的每个部分/模块都负责自己的注册。
但是,我会为 AutoMapper 配置创建一个新接口 IMapperConfiguration(单一职责)。同样使用反射来扫描这些程序集。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接