How to inject AutoMapper with Autofac?

前端 未结 2 2008
遥遥无期
遥遥无期 2021-01-19 17:25

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

相关标签:
2条回答
  • 2021-01-19 18:07

    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).

    0 讨论(0)
  • 2021-01-19 18:14

    .netcore 3 Autofac 5.1.2 AutoMapper 9.0.0 AutoMapperProfiles -> My profile name

    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<AutoMapperProfiles>().As<Profile>();
        builder.Register(c => new MapperConfiguration(cfg =>
        {
            foreach (var profile in c.Resolve<IEnumerable<Profile>>())
            {
                cfg.AddProfile(profile);
            }
        })).AsSelf().SingleInstance();
    
        builder.Register(c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve)).As<IMapper>().InstancePerLifetimeScope();
    }
    
    0 讨论(0)
提交回复
热议问题