Where should I put automapper code?

后端 未结 2 501
隐瞒了意图╮
隐瞒了意图╮ 2020-12-17 04:16

I\'m using Automapper in Asp.net mvc application. I have a question regard to the usage of automapper

from lots of sample code, I saw people use mapper Mapper.

相关标签:
2条回答
  • 2020-12-17 04:43

    For a previous question, I answered ASP.NET MVC with service layer and repository layer, where should the interfaces be defined?

    In my answer, I explained:

    [...] I have a typical structure like this:

    • MyProject.Core
    • MyProject.Domain
    • MyProject.DependencyInjection
    • MyProject.Infrastructure
    • MyProject.Web
    • MyProject.Tests

    The Infrastructure layer contains information about logging, emailing and data access. It will contain my ORM of choice. It's not business-logic stuff and it's not UI stuff. It's the railroad of my solution to get things done. It's on the outer layer but it only references the Core.

    In my case the infrastructure layer also houses Automapper. The core defines a simple interface (let's say IAutoMapper) and a simple object that exists in the infrastructure implements it and the object can be passed to the UI layer through dependency injection.

    However Jimmy Bogard (the creator of Automapper) said in AutoMapper 3.0, Portable Class Libraries and PlatformNotSupportedException

    [...] if you whine about UI projects shouldn’t reference this library directly because of some silly faux architect-y reason (even referencing a certain smelly round vegetable), I will drive to your house and slap you silly. Get off your high horse and start being productive.

    From what I understand he means that it's ok to reference Automapper from the UI layer. When he says "a certain smelly round vegetable" he is, of course, referring to Onion Architecture which Jimmy is not a big fan of.

    0 讨论(0)
  • 2020-12-17 05:02

    if you have service layer in your application, it's better to place the automapper in service layer. in any case try to use extension method for mapping your object by automapper like this:

    public static class Mapping
    {
    public static BankflowData CreateBankflowAdjustments(this BankflowData addedBankFlow)
          {
             var bankflow = Mapper.Map<Bankflow>(addedBankFlow);
             var newBankflow = Underlying.CreateBankFlowAdjustments(bankflow);
             return Mapper.Map<BankflowData>(newBankflow);
          }
    }
    

    it will make your code more readable and will separate your concerns. take this for more info

    0 讨论(0)
提交回复
热议问题