簡體   English   中英

如何使用 Autofac 注入 AutoMapper?

[英]How to inject AutoMapper with Autofac?

將 AutoMapper 注入其他層的正確方法是什么?

我看了這個博客帖子,但下面這段代碼導致異常

AutoMapper.dll 中發生了“AutoMapper.AutoMapperMappingException”類型的異常,但未在用戶代碼中處理

嘗試在服務層映射時。

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

我的 AutoFac 配置如下:

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));
    }
}

似乎您需要使用在容器中注冊的IConfiguration對象來創建這樣的映射:

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

我認為你應該在你的申請開始時這樣做。

這是在Config方法中配置事物的更好方法(IMO):

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));
}

我假設在最后一個示例中,您的類只需要訪問IMappingEngine (而不是IConfiguration ),因為您應該已經在Config方法(或應用程序啟動時的其他一些配置方法)中設置了所有映射。

.netcore 3 Autofac 5.1.2 AutoMapper 9.0.0 AutoMapperProfiles -> 我的個人資料名稱

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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM