我正在开发一个使用控制反转的 MVC 应用程序,因此广泛使用接口类型,具体实现由依赖解析器根据需要注入。实体接口继承自描述实体的一些基本管理功能的基本接口。ViewModel 也被广泛使用。
该应用程序使用 Automapper,我创建了从视图模型到各种实体接口的映射。映射配置正确验证。但是,当我调用 Automapper 执行映射时,代码失败并显示TypeLoadException
.
我相信 Automapper 能够映射到接口(见Jimmy Bogard)。
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();
}
}
抛出的异常是:
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)