Is it a bad practice or code smell to use an IoC container while installing dependencies?
This is my composition root:
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.
);
}
My AutoMapperProfileInstallerneeds to resolve a profile which contains dependencies in order to initialize the mapper
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);
}
});
}
}
This feels wrong on many levels, what would be a better way to initialize AutoMapper profiles?
The only thing wrong with that approach is that you manually specify the
IWindowsInstallerimplementations. Use reflection to find them andActivator.CreateInstanceto instantiate the implementations.It gives you a flexible configuration approach where each part/module in your system is responsible of it’s own registrations.
I would however create a new interface for the AutoMapper configuration
IMapperConfiguration(Single Responsibility). Use reflection to scan the assemblies for those too.