在何处放置AutoMapper.CreateMaps? [英] Where to place AutoMapper.CreateMaps?

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

问题描述

我用 AutoMapper ASP.NET MVC 应用程序。有人告诉我,我应该,因为他们有大量的开销移开 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.

我有一个Web层,服务层和数据层。每个它自己的项目。我使用 Ninject 来DI一切。我会在这两个网络层和业务层使用 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 ,跟单方法名为配置(),其中 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.

配置()方法,然后调用每个区域私人方法。

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

下面是我们的web层配置的例子:

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 seperated nicely.

那么你的的Global.asax

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

这有点像字的接口。 - 不能强制执行,但你想到吧,这样你就可以code(和重构)如果neccessary

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

编辑:

想我要指出,我现在使用AutoMapper 型材,所以上面的例子就变成了:

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>();
    }
}

更清洁/更强劲。

Much cleaner/more robust.

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

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