我在让 aufotac 注入我的 autopmapper 类型转换器时遇到问题。我尝试了一些不同的方法,但我目前无法使用下面的代码。我最接近找到解决方案的是下面的代码(从http://thoai-nguyen.blogspot.se/2011/10/autofac-automapper-custom-converter-di.html借来的小片段)。他的样本似乎可以 1:1 工作,但无法找到我缺少的东西。像往常一样提取相关位,如果不够,请告诉我。
我的 autofac 引导程序:
public class AutoFacInitializer
{
public static void Initialize()
{
//Mvc
var MvcContainer = BuildMvcContainer();
DependencyResolver.SetResolver(new AutofacDependencyResolver(MvcContainer));
//Web API
var ApiContainer = BuildApiContainer();
var ApiResolver = new AutofacWebApiDependencyResolver(ApiContainer);
GlobalConfiguration.Configuration.DependencyResolver = ApiResolver;
}
private static IContainer BuildApiContainer()
{
var builder = new ContainerBuilder();
var assembly = Assembly.GetExecutingAssembly();
builder.RegisterApiControllers(assembly);
return BuildSharedDependencies(builder, assembly);
}
private static IContainer BuildMvcContainer()
{
var builder = new ContainerBuilder();
var assembly = typeof (MvcApplication).Assembly;
builder.RegisterControllers(assembly);
builder.RegisterFilterProvider();
return BuildSharedDependencies(builder, assembly);
}
private static IContainer BuildSharedDependencies(ContainerBuilder builder, Assembly assembly)
{
//----Build and return container----
IContainer container = null;
//Automapper
builder.RegisterAssemblyTypes(assembly).AsClosedTypesOf(typeof(ITypeConverter<,>)).AsSelf();
AutoMapperInitializer.Initialize(container);
builder.RegisterAssemblyTypes(assembly).Where(t => typeof(IStartable).IsAssignableFrom(t)).As<IStartable>().SingleInstance();
//Modules
builder.RegisterModule(new AutofacWebTypesModule());
builder.RegisterModule(new NLogLoggerAutofacModule());
//Automapper dependencies
builder.Register(x => Mapper.Engine).As<IMappingEngine>().SingleInstance();
//Services, repos etc
builder.RegisterGeneric(typeof(SqlRepository<>)).As(typeof(IRepository<>)).InstancePerDependency();
container = builder.Build();
return container;
}
}
我的 Automap 引导程序/初始化程序:
namespace Supportweb.Web.App_Start
{
public class AutoMapperInitializer
{
public static void Initialize(IContainer container)
{
Mapper.Initialize(map =>
{
map.CreateMap<long?, EntityToConvertTo>().ConvertUsing<LongToEntity<NavigationFolder>>();
map.ConstructServicesUsing(t => container.Resolve(t));
});
Mapper.AssertConfigurationIsValid();
}
}
}
我试图开始工作的类型转换器:
public class LongToEntity<T> : ITypeConverter<long?, T>
{
private readonly IRepository<T> _repo;
public LongToEntity(IRepository<T> repo)
{
_repo = repo;
}
public T Convert(ResolutionContext context)
{
long id = 0;
if (context.SourceValue != null)
id = (long)context.SourceValue;
return _repo.Get(id);
}
}
除了转换器,所有映射都可以正常工作。该错误似乎表明我缺少 ioc 参考,但我已经尝试过,但提到的 ITypeConverter<,> 和 LongToEntity<> 以及似乎没有帮助的变体。