开发者

ASP.NET MVC 2 Automapper Placement

开发者 https://www.devze.com 2023-01-18 16:37 出处:网络
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 cons

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?


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消