问题描述
我确定这个问题已经问过好几次了,但是我对此一无所知。我正在尝试将EF对象的属性自动映射到已定义的接口。我使用简单的注入器作为IOC框架的选择。 (获胜表格)
我已经在program.cs中注册了我的界面。
container = new Container();
container.Register<IBob,Bob>();
...
并将容器的实例传递到我正在执行自动映射的类中。
public ModelService(IDataRepository repo,Container container)
{
// create a reference to the repository
this.Repository = repo;
var config = new MapperConfiguration(cfg =>
{
// pass the reference into the constructor service.
qcfg.ConstructServicesUsing(type => container.GetInstance(type));
cfg.AddProfile<ModelConfig>();
});
mapper = new Mapper(config);
}
个人资料类看起来有点像这样...
public class ModelConfig : Profile
{
public ModelsConfig()
{
// mapping deFinition for product buy
this.CreateMap<Entity.BobEF,IBob>()
.ForMember(destination => destination.UniqueIdentifier,option => option.MapFrom(source => source.BobID))
.ReverseMap();
}
因此,我期望automapper使用该容器为IBob创建一个具体的类,因为已经在BI自举中声明了该类,并且应该使用“ container.GetInstance()”方法来解析该接口,但是我实际上在使用类型为Proxy_MyProject.IBob_232342的IBob类的代理表示中得到了什么
我真的不了解automapper documentation,因为我是使用自动映射器的新手。
非常感谢任何帮助。
此致
蒂姆
编辑 :(正在使用的模型类示例)
// shows the basic interface for a product
public interface IProduct : IModel
{
string Name { get; set; }
Isupplier supplier { get; set; }
}
// shows the concrete implementation including the
// exposed property being of type Isupplier
public class Product : Model,IProduct
{
public string Name
{
get;
set;
}
public Isupplier supplier
{
get;
set;
}
}
解决方法
ConstructServicesUsing
本身仅适用于值解析器,成员值解析器,类型转换器等。与您的需求无关。您想要:
CreateMap<Entity.BobEF,IBob>().ConstructUsingServiceLocator();
这也将导致您以相同的方式构造目标对象。 但是我必须同意@JoepVerhoeven,这听起来像是工程过度。
,自动映射器返回代理对象的原因是因为您正在将类映射到接口,而自动映射器不知道要使用IBob
的哪种实现。
@Lucian Bargaoanu提供的答案是正确的,但这需要ConstructServicesUsing
和ConstructUsingServiceLocator
的组合。我已经在这里阅读文档了。enter link description here,但不明白这意味着我们应该在映射声明中使用附加的ConstructUsingServiceLocator
。
示例:
// Or marker types for assemblies:
var config = new MapperConfiguration(cfg =>
{
// pass the reference into the constructor service.
cfg.ConstructServicesUsing(type => container.GetInstance(type));
//cfg.ConstructServicesUsing()
cfg.AddProfile(new BusinessModelsConfig(this.Repository.Context));
});
此配置包含在BusinessModelsConfig中。
// mapping definition for product buy
this.CreateMap<Entity.ProductBuy,IProductBuy>()
.ForMember(destination => destination.UniqueIdentifier,option => option.MapFrom(source => source.ProductBuyID))
.ForMember(destination => destination.Status,option => option.MapFrom(source => source.BuyStatus))
.ForMember(destination => destination.TimeStamp,option => option.MapFrom(source => source.ts))
.ConstructUsingServiceLocator();
对于那些还需要映射回实体以使更改可以反映在持久层内的人来说,this article被证明对于理解如何实现这一点非常宝贵,尽管自动映射器可能不是实现此目的的最佳工具。本文相当陈旧,欢迎任何提供不同观点的信息。