Eon*_*dan 4 c# autofac automapper automapper-4
我尝试过各种各样的排列,但我目前的配置(因为它与AutoMapper有关)是这样的:
builder.RegisterAssemblyTypes().AssignableTo(typeof(Profile)).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();
builder.RegisterType<MappingEngine>().As<IMappingEngine>();
Run Code Online (Sandbox Code Playgroud)
我有一个构造函数使用IMapper mapper,但我继续得到YSOD:
None of the constructors found with'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'
on type '' can be invoked with the available services and parameters:
Cannot resolve parameter 'AutoMapper.IMapper mapper' of constructor
'Void .ctor(...,...,..., AutoMapper.IMapper)'.
Run Code Online (Sandbox Code Playgroud)
这个类在没有automapper引用的情况下工作得很好,所以我确定麻烦在于我的automapper配置.
我不确定我在这里缺少什么,因为我对AutoFac和AutoMapper都很新.
编辑:
我也尝试过:
builder.Register(c => new MapperConfiguration(cfg =>
{
cfg.CreateMap<IdentityUser, AspNetUser>().ReverseMap();
})).AsSelf().SingleInstance();
builder.Register(ctx => ctx.Resolve<MapperConfiguration>().CreateMapper()).As<IMapper>();
//I've tried both of these lines separately, neither work
builder.Register(c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve)).As<IMapper>().InstancePerLifetimeScope();
Run Code Online (Sandbox Code Playgroud)
我还尝试根据评论中的建议手动添加配置文件
正如我在评论中提到的,您的AutoFac代码似乎是正确的(除了程序集扫描部分).
我创建了以下测试应用程序,它实际上运行时没有任何异常,并将3放入"输出"窗口(按预期):
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; }
}
}
Run Code Online (Sandbox Code Playgroud)
我建议在版本控制中创建一个新的应用程序分支,然后剥离它直到它工作.