views:

104

answers:

1

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?

+1  A: 

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
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?
Smith
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
Where do you perform your repo initialization so that it is 'per http request'?
Smith
Added a bit more information
BuildStarted
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.
Smith
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

related questions