在哪里放置 AutoMapper.CreateMaps? [英] Where to place AutoMapper.CreateMaps?

查看:29
本文介绍了在哪里放置 AutoMapper.CreateMaps?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ASP.NET MVC 应用程序中使用 AutoMapper.有人告诉我我应该将 AutoMapper.CreateMap 移到其他地方,因为它们有很多开销.我不太确定如何设计我的应用程序以将这些调用放在 1 个地方.

I'm using AutoMapper in an ASP.NET MVC application. I was told that I should move the AutoMapper.CreateMap elsewhere as they have a lot of overhead. I'm not too sure how to design my application to put these calls in just 1 place.

我有一个网络层、服务层和一个数据层.每一个都有自己的项目.我使用 Ninject 来 DI 一切.我将在 Web 层和服务层中使用 AutoMapper.

I have a web layer, service layer and a data layer. Each a project of its own. I use Ninject to DI everything. I'll utilize AutoMapper in both web and service layers.

那么您对 ​​AutoMapper 的 CreateMap 的设置是什么?你把它放在哪里?你怎么称呼它?

So what are your setup for AutoMapper's CreateMap? Where do you put it? How do you call it?

推荐答案

没关系,只要是静态类即可.一切都与约定有关.

Doesn't matter, as long as it's a static class. It's all about convention.

我们的约定是每个层"(网络、服务、数据)都有一个名为 AutoMapperXConfiguration.cs 的文件,有一个名为 Configure 的方法(),其中X是层.

Our convention is that each "layer" (web, services, data) has a single file called AutoMapperXConfiguration.cs, with a single method called Configure(), where X is the layer.

Configure() 方法然后为每个区域调用 private 方法.

The Configure() method then calls private methods for each area.

以下是我们的网络层配置示例:

Here's an example of our web tier config:

public static class AutoMapperWebConfiguration
{
   public static void Configure()
   {
      ConfigureUserMapping();
      ConfigurePostMapping();
   }

   private static void ConfigureUserMapping()
   {
      Mapper.CreateMap<User,UserViewModel>();
   } 

   // ... etc
}

我们为每个聚合"(用户、帖子)创建了一个方法,因此可以很好地分开.

We create a method for each "aggregate" (User, Post), so things are separated nicely.

然后你的Global.asax:

AutoMapperWebConfiguration.Configure();
AutoMapperServicesConfiguration.Configure();
AutoMapperDomainConfiguration.Configure();
// etc

它有点像文字界面" - 无法强制执行,但您期望它,因此您可以在必要时进行编码(和重构).

It's kind of like an "interface of words" - can't enforce it, but you expect it, so you can code (and refactor) if necessary.

只是想我会提到我现在使用 AutoMapper profiles,所以上面的例子变成:>

Just thought I'd mention that I now use AutoMapper profiles, so the above example becomes:

public static class AutoMapperWebConfiguration
{
   public static void Configure()
   {
      Mapper.Initialize(cfg =>
      {
        cfg.AddProfile(new UserProfile());
        cfg.AddProfile(new PostProfile());
      });
   }
}

public class UserProfile : Profile
{
    protected override void Configure()
    {
         Mapper.CreateMap<User,UserViewModel>();
    }
}

更干净/更健壮.

这篇关于在哪里放置 AutoMapper.CreateMaps?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆