我应该使用哪个 PreApplicationStartMethod?
我注意到,当我将 NuGet 中的 StructureMap 安装到 ASP.NET MVC3 项目中时,Dave Ebbo 的 WebActivator 包也被安装添加为依赖项。
WebActivator 提供了一个 PreApplicationStartMethod 属性,在安装时添加的样板代码中,它用于在自己的类中初始化 IoC 容器和依赖解析器,而不是在 Global.asax 中执行此操作 的 Application_Start
方法。
鉴于 ASP.NET 4 已经拥有自己的 System。 Web.PreApplicationStartMethodAttribute
为什么 WebActivator 有必要提供自己的版本并让 StructureMap 使用它?
我猜我没有使用WebActivator的变体?
为 Darin 添加了代码:
using System.Web;
using System.Web.Mvc;
using StructureMap;
[assembly: WebActivator.PreApplicationStartMethod(
typeof(MyMvcApp.App_Start.StructuremapMvc), "Start")]
// or
[assembly: PreApplicationStartMethod(
typeof(MyMvcApp.App_Start.StructuremapMvc), "Start")]
namespace MyMvcApp.App_Start {
public static class StructuremapMvc {
public static void Start() {
var container = (IContainer) IoC.Initialize();
DependencyResolver.SetResolver(new SmDependencyResolver(container));
}
}
}
I noticed that when I installed StructureMap from NuGet into my ASP.NET MVC3 project, Dave Ebbo's WebActivator package was also added as a dependency.
WebActivator provides a PreApplicationStartMethod
attribute and, in the boilerplate code added at install time, it is used to initialise the IoC container and dependency resolver in it's own class, instead of doing this inside Global.asax
's Application_Start
method.
Given that ASP.NET 4 already has its own System.Web.PreApplicationStartMethodAttribute
why was it necessary for WebActivator to supply its own version and for StructureMap to use that?
I am guessing I don't have to use WebActivator's variant?
Added code for Darin:
using System.Web;
using System.Web.Mvc;
using StructureMap;
[assembly: WebActivator.PreApplicationStartMethod(
typeof(MyMvcApp.App_Start.StructuremapMvc), "Start")]
// or
[assembly: PreApplicationStartMethod(
typeof(MyMvcApp.App_Start.StructuremapMvc), "Start")]
namespace MyMvcApp.App_Start {
public static class StructuremapMvc {
public static void Start() {
var container = (IContainer) IoC.Initialize();
DependencyResolver.SetResolver(new SmDependencyResolver(container));
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ASP.NET MVC 3 中 DI 容器的 NuGet 包通常更喜欢使用 WebActivator 以避免弄乱
Application_Start
中可能拥有的任何现有代码。 Ninject 使用完全相同的方法。您的应用程序中可以有多个
WebActivator.PreApplicationStartMethod
属性,而在 .NET 4.5 之前,可以有一个System.Web.PreApplicationStartMethodAttribute
属性。NuGet packages for DI containers in ASP.NET MVC 3 usually prefer to use WebActivator to avoid messing with any existing code that you might have in
Application_Start
. Ninject uses exactly the same approach.You can have multiple
WebActivator.PreApplicationStartMethod
attributes in your application and prior to .NET 4.5 a singleSystem.Web.PreApplicationStartMethodAttribute
.