c# - 如何使用 Autofac 注入(inject) AutoMapper?

标签 c# asp.net-mvc dependency-injection automapper autofac

将AutoMapper注入(inject)其他层的正确方法是什么?

我读了这个博客 post , 但是此代码导致下面的异常

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

在服务层尝试映射时。

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

最佳答案

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

关于c# - 如何使用 Autofac 注入(inject) AutoMapper?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33980760/

相关文章:

c# - 列表框.SelectedItem

c# - 找不到对象实例上的方法

c# - 插入 MS Access 语句中的语法错误

angular - 覆盖特定测试的 TestBed 提供程序

c# - 应该如何使一个具有依赖项的类可以在不膨胀的情况下进行单元测试?

swift - 在 Swift 中使用 DI 时避免胖初始化器

c# - 模式 : "if (obj is Abc && (obj as Abc) ...)" 的方法

asp.net-mvc - 通过 Nuget 添加后 MVC 6 引用 Jquery

javascript - Url.Action 没有给我实际的 Url

.net - Cassini (VS WebDev) 在不同线程上执行 BeginRequest 和 EndRequest