3

I am using Automapper to convert between my EF4 Models and my ViewModels. Automapper needs map relationships declared and I find myself copy/pasting them inside every controller's constructor.

Mapper.CreateMap<CoolObject, CoolObjectViewModel>();

Where can I place the mapping declarations so they will only be called once and not every time a controller is instantiated? Is this possible?

John
  • 159
  • 10

1 Answers1

5

You can put it in the application_start() of the global.asax

Currently I have a static method that I call from the application_start that initializes all my mappings. Library.AutoMapping.RegisterMaps();

AutoMapper.Mapper.CreateMap(typeof(CoolObject), typeof(CoolObjectViewModel));

AutoMapper.Mapper.CreateMap<CoolObject, CoolObjectViewModel>()
    .ForMember(d => d.Property1, f => f.MapFrom(s => s.Property1))
    .ForMember(d => d.Property2, f => f.MapFrom(s => s.Property2))
    .ForMember(d => d.Property3, f => f.MapFrom(s => s.Property3));

So my Controller looks something like this. You'll notice that the HomeController constructor requires an IDataContext. I register IDataContext with Ninject on a RequestScope level and a DataContext is instantiated for me and injected into my controller. This is where my request level repository comes from.

public class HomeController : Controller {

    IDataContext dataContext;

    public HomeController(IDataContext dataContext) {
        this.dataContext = dataContext;
    }
}

I have a slightly more detailed explanation about Ninject here http://buildstarted.com/2010/08/24/dependency-injection-with-ninject-moq-and-unit-testing/

Buildstarted
  • 26,529
  • 10
  • 84
  • 95
  • Thank you for your answer. My maps depend on initializing a repository typed as one of my EF4 table objects. I want to scope the repository on a 'per request' basis. Will these maps be valid if I then use another set of repos for my CRUD operations? – John Oct 02 '10 at 02:38
  • That's pretty much the same thing I'm doing. I'm using Ninject to initialize my repository and I haven't had any issues with mapping. However, I use `Mapper.CreateMap(typeof(CoolOject), typeof(CoolObjectViewModel))` – Buildstarted Oct 02 '10 at 02:48
  • Where do you perform your repo initialization so that it is 'per http request'? – John Oct 02 '10 at 02:55
  • Ok, my controllers also take injected ObjectContexts but I wasn't aware of the RequestScope (Ninject?) I will read your other article now. Thank you. – John Oct 02 '10 at 03:07
  • Yeah, Ninject has several scopes. The InRequestScope() creates an instance per web request and will no longer exist when the request is over. Other scopes are InTransientScope (create a new instance on each time one is needed), InSingletonScope (create a single instance and return that instance anytime it’s requested), and InThreadScope (create an instance per thread). – Buildstarted Oct 02 '10 at 03:09