mohsen dorparasti
mohsen dorparasti

Reputation: 8415

configure autoMapper.Mapping once in application

is there any way to map 2 Models once in my application ( Mapper.CreateMap()) for example in global.asax and then wherever necessary just call Mapper.Map() in codes ?

Upvotes: 0

Views: 313

Answers (1)

ngm
ngm

Reputation: 7487

Yes you can, and in fact that's the recommended way to configure AutoMapper. Creating the initial mappings is the (relatively) expensive part of AutoMapper, so you want to do it only once.

As you suggest, Global.asax is a good place to do it. Although it's a good idea to put it in a separate class, for example Bootstrapper, that the Application_Start method calls into, such that this class and method can also be called from your unit tests.

From the AutoMapper docs:

Where do I configure AutoMapper? If you're using the static Mapper method, configuration only needs to happen once per AppDomain. That means the best place to put the configuration code is in application startup, such as the Global.asax file for ASP.NET applications. Typically, the configuration bootstrapper class is in its own class, and this bootstrapper class is called from the startup method.

See also this question, which has some good ideas including a suggestion from Jimmy Bogard, who wrote AutoMapper.

Upvotes: 1

Related Questions