ASP.NET MVC 2 自动映射器放置
我正在使用 Automapper 在 EF4 模型和 ViewModel 之间进行转换。 Automapper 需要声明映射关系,我发现自己将它们复制/粘贴到每个控制器的构造函数中。
Mapper.CreateMap<CoolObject, CoolObjectViewModel>();
我可以在哪里放置映射声明,以便它们只被调用一次,而不是每次实例化控制器时?这可能吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将其放在
global.asax
的application_start()
中。目前,我有一个从 application_start 调用的静态方法,该方法初始化所有映射。
Library.AutoMapping.RegisterMaps();
所以我的控制器看起来像这样。您会注意到 HomeController 构造函数需要 IDataContext。我在 RequestScope 级别上向 Ninject 注册 IDataContext,并为我实例化 DataContext 并将其注入到我的控制器中。这就是我的请求级别存储库的来源。
我在这里有关于 Ninject 的稍微更详细的解释 http://buildstarted.com/2010/08/24/dependency-injection-with-ninject-moq-and-unit-testing/
You can put it in the
application_start()
of theglobal.asax
Currently I have a static method that I call from the application_start that initializes all my mappings.
Library.AutoMapping.RegisterMaps();
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.
I have a slightly more detailed explanation about Ninject here http://buildstarted.com/2010/08/24/dependency-injection-with-ninject-moq-and-unit-testing/