[英]Simple Injector & Automapper
我相信这个问题已经被问过好几次了,但我在这个问题上陷入了困境。 我正在尝试将属性从 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);
}
profile 类看起来有点像这样......
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 的新手。
非常感谢任何帮助。
问候,
蒂姆
编辑:(正在使用的模型类示例)
// 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,这听起来像是过度设计。
automapper 返回 Proxy 对象的原因是因为您将类映射到接口,而 automapper 不知道要使用IBob
哪个实现。
@Lucian Bargaoanu 提供的答案是正确的,但这需要ConstructServicesUsing
和ConstructUsingServiceLocator
的组合。 我已经阅读了文档here ..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();
对于那些还需要映射回实体以便更改可以反映在持久层中的人, 本文证明对于理解如何实现这一点非常有价值,尽管 automapper 可能不是最好的工具。 这篇文章相当陈旧,我欢迎任何提供不同视角的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.