DAL 中的 AutoMapper:何时使用 Mapper.Reset()?
我在生成的数据访问层中使用 AutoMapper。效果很好。在另一层中使用 AutoMapper 并实现在 DAL 中使用 Mapper.CreateMap
注意:在 DAL 中使用 AutoMapper 有一些特定的选项,例如我的其他层不应使用的许多 .ForMember(...) 调用(如果没有 Mapper.Reset()
他们会重用这些选项)。
I'm using AutoMapper in a generated Data Access Layer. That works fine. It was a little confusing when using AutoMapper in another layer and realizing the mappings created in the DAL with Mapper.CreateMap<T1, T2>()
were still present. I see Mapper.Reset()
which will remove these however I'd rather not have to have the other layers worry about the DAL. Would the best practice be to put a Mapper.Reset()
before and after my mapping operations in the DAL? Or is there a way to give these DAL mappings a non-default key to let them persist but not interfere with the use of AutoMapper in other layers?
Note: The use of AutoMapper in the DAL has some specific options such as a number of .ForMember(...) calls that my other layers should not use (without a Mapper.Reset()
they would reuse these options).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
AutoMapper 作为单例/单个实例工作。但这真的很重要吗?
编辑:这可能会帮助您使用配置文件 如果您的其他层不太担心 DAL 类,
那么它们很可能不会在 DAL 类的实例上调用 Map 。
如果您调用 Reset(),那么您的 DAL 类在下次需要执行某些映射时将需要重新声明它们,这将增加额外的非常不必要的开销。
编辑:如果您在每个 DAL 调用开始时调用 Reset,那么您只能有一个单线程数据访问策略。如果您在另一个 DAL 项目的映射中间调用 Reset,那么您显然会破坏这一点 - 因此您必须锁定每个 DAL 方法。
这不是使用 Automapper 的方法,所以我倾向于要么研究这些配置文件,要么不一起使用它们。
另外:您可以发布一个示例代码来说明进行大量多重映射时出现的问题吗?两种类型之间是否存在不同的映射策略,具体取决于它们在 DAL 中的调用位置?
AutoMapper works as a singleton/single instance. Does it really matter though?
EDIT : This may help you Using Profiles in Automapper to map the same types with different logic
If your other layers aren't worried so much about the DAL classes chances are they aren't going to be calling Map on an instance of the DAL class anyway.
If you call Reset() then your DAL classes will need to restate them when they next need to do some mapping which will add extra very unnecessary overhead.
EDIT : If you call Reset at the start of every DAL call then you can only have a single threaded Data Access strategy. If you call Reset in the middle of a mapping for another DAL project then you are going to obviously break this - so you will have to lock on every DAL method.
This is not the way to use Automapper so I would be leaning towards either looking into those profiles, or not using it all together.
ALSO : Can you post a sample code for what is wrong with having lots and lots of multiple mappings going on? Are there different mapping strategies between two types depending on where in the DAL they are being called from?