Pau*_*lor 11 interface automapper
我正在研究一个使用Inversion of Control的MVC应用程序,因此广泛使用了接口类型,具体实现由依赖解析器根据需要注入.实体接口继承自描述实体的一些基本管理功能的基本接口.ViewModels也被广泛使用.
该应用程序使用Automapper,我已经创建了从视图模型到各种实体接口的映射.映射配置正确验证.但是,当我调用Automapper执行映射时,代码失败了TypeLoadException.
我相信Automapper能够映射接口(见本吉米博加德).
似乎Automapper代理生成器可能已省略将MyMethod()添加到代理,这会在Reflection尝试创建类型时导致异常.
如果不是这样,我该如何让这张地图发挥作用?我错过了一些明显的事吗?
这是一个简化的控制台应用程序,用于演示场景,并在运行时重现错误:
public interface IEntity
{
string Foo { get; set; }
string Bar { get; set; }
string MyMethod();
}
public class MyEntity : IEntity
{
public string Foo { get; set; }
public string Bar { get; set; }
public string MyMethod()
{
throw new NotImplementedException();
}
}
public class MyViewModel
{
public string Foo { get; set; }
public string Bar { get; set; }
}
class Program
{
static void Main(string[] args)
{
AutomapperConfig();
MyViewModel vm = new MyViewModel { Foo = "Hello", Bar = "World" };
IEntity e = Mapper.Map<MyViewModel, IEntity>(vm);
Console.WriteLine(string.Format("{0} {1}", e.Foo, e.Bar));
}
private static void AutomapperConfig()
{
Mapper.Initialize(cfg => {
cfg.CreateMap<MyViewModel, IEntity>();
});
Mapper.AssertConfigurationIsValid();
}
}
Run Code Online (Sandbox Code Playgroud)
抛出的异常是:
InnerException: System.TypeLoadException
HResult=-2146233054
Message=Method 'MyMethod' in type 'Proxy<AutomapperException.IEntity_AutomapperException_Version=1.0.0.0_Culture=neutral_PublicKeyToken=null>' from assembly 'AutoMapper.Proxies, Version=0.0.0.0, Culture=neutral, PublicKeyToken=be96cd2c38ef1005' does not have an implementation.
Source=mscorlib
TypeName=Proxy<AutomapperException.IEntity_AutomapperException_Version=1.0.0.0_Culture=neutral_PublicKeyToken=null>
StackTrace:
at System.Reflection.Emit.TypeBuilder.TermCreateClass(RuntimeModule module, Int32 tk, ObjectHandleOnStack type)
at System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
at System.Reflection.Emit.TypeBuilder.CreateType()
at AutoMapper.Impl.ProxyGenerator.CreateProxyType(Type interfaceType)
at AutoMapper.Impl.ProxyGenerator.GetProxyType(Type interfaceType)
at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.CreateObject(ResolutionContext context)
at AutoMapper.Mappers.TypeMapObjectMapperRegistry.NewObjectPropertyMapMappingStrategy.GetMappedObject(ResolutionContext context, IMappingEngineRunner mapper)
at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.Map(ResolutionContext context, IMappingEngineRunner mapper)
at AutoMapper.Mappers.TypeMapMapper.Map(ResolutionContext context, IMappingEngineRunner mapper)
at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)
Run Code Online (Sandbox Code Playgroud)
使用接口作为目标时,AutoMapper将为您创建代理类型,但这仅支持属性.
要解决这个问题,您可以告诉AutoMapper如何使用构图上的ConstructUsing构建目标对象,因此在上面的示例中,您的创建地图将如下所示......
cfg.CreateMap<MyViewModel, IEntity>().ConstructUsing((ResolutionContext rc) => new MyEntity());
Run Code Online (Sandbox Code Playgroud)
作为参考我从这篇SO文章中找到了这个:https://stackoverflow.com/a/17244307/718672