2

In advance, I apologize if this question has been answered already somewhere else; But I've been finding a lot of mixed results on the matter.

I'm using:

  • .net Framework 4.6.1
  • Microsoft.AspNet.Mvc 5.2.6
  • AutoMapper 6.2.2
  • EntityFramework 6.2.0

I'm quite new to both ASP.net and C# and lately I've become a fan of the AutoMapper package. I've mostly been using it to convert my Entities I get from my ApplicationDbContext to my DTO's (Data Transfer Objects) or ViewModel's.

I now use this setup in my applications to initialize and use the Mapper in my Controller's:

Global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        Mapper.Initialize(AutoMapperConfiguration.Configure);

        // Other configuration for MVC application...
    }
}

AutoMapperConfiguration.cs

public static class AutoMapperConfiguration
{
    public static void Configure(IMapperConfigurationExpression config)
    {
        config.CreateMap<Post, Post.DetailsViewModel>().ForMember(post => post.CanEdit, cfg => cfg.ResolveUsing((src, dst, arg3, context) => context.Options.Items["UserId"]?.ToString() == src.UserId));
    }
}

PostsController.cs and Post.cs

public class PostsController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        Post post = db.Posts.Find(id);

        if (post == null)
        {
            return HttpNotFound();
        }

        return View(Mapper.Map<Post.DetailsViewModel>(post, options => options.Items["UserId"] = User.Identity?.GetUserId()));
    }
}


// Post.cs

public class Post
{
    public int Id { get; set; }

    public string UserId { get; set; }

    public virtual ApplicationUser User { get; set; }

    public string Title { get; set; }

    public string Content { get; set; }

    public DateTime PostedAt { get; set; } = DateTime.Now;

    public class DetailsViewModel
    {
        public int Id { get; set; }

        public string UserId { get; set; }

        public ApplicationUser User { get; set; }

        public string Title { get; set; }

        public string Content { get; set; }

        /// <summary>
        /// A value indicating whether the current logged in user can edit the model
        /// </summary>
        public bool CanEdit { get; set; }

        public DateTime PostedAt { get; set; }
    }
}

Code summary

I am configuring my Mapper in a static class (AutoMapperConfiguration) that contains a Config method which is invoked from the Global.asax.cs file and maps the required classes.

Then, in my Controller I use the static method Mapper.Map to map my Post to it's DetailsViewModel.

The question

How does this usage of AutoMapper (via static method Mapper.Map) impact performance, and is there a better way to do this?

Some clarifications:

For example: What if I get 100 requests per second on different controller actions; As far as I know every request will have a separate thread but will access the same memory for the Mapper.Map method (if I am correct). Which - to my knowledge - means performance will be impacted severely.

A question I have already looked at but got mixed results from:

Non-static AutoMapper and ASP.NET MVC -> Where to place AutoMapper.CreateMaps?

Please correct me if I'm wrong on any of this.

2 Answers 2

8

How does this usage of AutoMapper (via static method Mapper.Map) impact performance, and is there a better way to do this?

Your usage of AutoMapper is correct. Initialization at the application startup is a best practice to respect. By calling Mapper.Initialize you are initializing a mapper which is an static instance of IMapper interface (accessible through Mapper.Instance static property). When using the static members from Mapper class you are dealing with Mapper.Instance and it is the same instance for all objects into the same AppDomain. You will not impact performance as long as long you're into the same AppDomain and not doing some time consuming in your mapping configuration (someone may put some business logic or time consuming logic into AfterMap, BeforeMap, ResolveUsing, MapFrom etc.).

What if I get 100 requests per second on different controller actions; As far as I know every request will have a separate thread but will access the same memory for the Mapper.Map method (if I am correct). Which - to my knowledge - means performance will be impacted severely.

Your application use one instance of AppDomain, each request will got a new thread but that thread will run in the same AppDomain that started your application, the one that executed the Application_Start method and finally you'll get the same instance of Mapper.Instance so your configuration's plan will only be compiled and cached when the first request arrive. Only the first request will be impacted not the following. Other requests will use the cached configuration's plan. So no performance impact as long as you're in the same AppDomain and not using some time consuming logic into custom mapping alternative that AutoMapper allows you to do.

Also AutoMapper comes with some cnfigurations that can be activated or deactivated and gain performance.

Explicit compilation

As I already said, the first request that uses mapping will compile your configuration's plan. As AutoMapper's documentation says:

Because expression compilation can be a bit resource intensive, AutoMapper lazily compiles the type map plans on first map. However, this behavior is not always desirable, so you can tell AutoMapper to compile its mappings directly. For a few hundred mappings, this may take a couple of seconds.

You can explicitly compile the plan by doing this just after your mapping configuration:

Mapper.Configuration.CompileMappings();

I use this and combine it with application "warming" where my application is started automatically instead of waiting for the first request to do mapping and compiles my configuration's plan. You can look at this answer for how to enable that feature.

Inline mapping

With 6.2.0, AutoMapper came with a new feature which is called inline mapping which allow you to create a type map on the fly instead of configuring them through the call of Mapper.Initialize method. Because an inline mapping is created on the fly so they are compiled at that time so the gain you're looking for explicitly compiling your plan does not help a lot. So what I do in my projects, I deactivate this feature so anyone can't inadvertisely used it. To deactivate it, you do this:

cfg.CreateMissingTypeMaps = false;

Edit 26/02/2019

AutoMapper creator just added a blog post today (26/02/2019) about AutoMapper Usage Guidelines. Must read.

0
0

I don't know if this can help you, but i've updated the AutoMapper to version 8.1.0 and the performance is better. I've seen that performance was corrected on version 7.0.0 but in the latest version can be better. Depends on your implementation the impact of update is minimal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.