How to inject AutoMapper with Autofac?

2019-02-25 06:48发布

问题:

What is the proper way to inject AutoMapper to other layers?

I read this blog post , but this code cause exception below

An exception of type 'AutoMapper.AutoMapperMappingException' occurred in AutoMapper.dll but was not handled in user code

when try mapping in service layer.

List<StudentViewModel> list2 = _mapper.Map<List<StudentViewModel>>(list);

My AutoFac configuration like below:

public static class DependencyRegistration
{
    public static void Config()
    {
        var builder = new ContainerBuilder();

        builder.RegisterControllers(typeof(MvcApplication).Assembly);


        builder.RegisterType<TypeMapFactory>().As<ITypeMapFactory>();
        builder.RegisterType<ConfigurationStore>().As<ConfigurationStore>().WithParameter("mappers", MapperRegistry.Mappers).SingleInstance();
        builder.Register((ctx, t) => ctx.Resolve<ConfigurationStore>()).As<IConfiguration>().As<IConfigurationProvider>();
        builder.RegisterType<MappingEngine>().As<IMappingEngine>();

        //...
        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }
}

回答1:

It seems that you need to use the IConfiguration object that is registered in the container to create the maps like this:

var configuration = container.Resolve<IConfiguration>();
configuration.CreateMap<Student, StudentViewModel>();

I think that you should be doing this at the start of your application.

Here is a better way (IMO) to configure things in the Config method:

public static void Config()
{
    var configuration_store = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);

    var mapping_engine = new MappingEngine(configuration_store);

    configuration_store.CreateMap<Student, StudentViewModel>();

    var builder = new ContainerBuilder();

    builder.RegisterInstance(mapping_engine).As<IMappingEngine>();

    //...
    var container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}

I am assuming in the last example, that your classes need access only to IMappingEngine (and not IConfiguration), since your should already setup all mappings in the Config method (or some other configuration method at application startup).