Cannot resolve AutoMapper.IMapper using AutoMapper 4.2 with Autofac

北城以北 提交于 2019-12-05 13:38:39

As I mentioned in a comment, your AutoFac code appears to be correct (except for the assembly scanning portion).

I created the following test app, and it does in fact run without any exceptions and puts a 3 into the Output window (as intended):

using System.Diagnostics;
using Autofac;
using AutoMapper;

namespace Sandbox
{
    public partial class App
    {
        public App()
        {
            var builder = new ContainerBuilder();
            builder.Register(
                c => new MapperConfiguration(cfg =>
                {
                    cfg.AddProfile(new TestProfile());
                }))
                .AsSelf()
                .SingleInstance();

            builder.Register(
                c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve))
                .As<IMapper>()
                .InstancePerLifetimeScope();

            builder.RegisterType<MappingEngine>()
                .As<IMappingEngine>();

            builder.RegisterType<Test>().AsSelf();

            var container = builder.Build();
            container.Resolve<Test>();
        }
    }

    public class TestProfile : Profile
    {
        protected override void Configure()
        {
            CreateMap<Source, Destination>();
        }
    }

    public class Test
    {
        public Test(IMapper mapper)
        {
            var source = new Source { Id = 3 };
            var destination = mapper.Map<Destination>(source);
            Debug.Print(destination.Id.ToString());
        }
    }

    public class Source
    {
        public int Id { get; set; }
    }

    public class Destination
    {
        public int Id { get; set; }
    }
}

I would suggest creating a new branch of your app in version control and stripping things out until it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!