Asp.net
我應該使用哪個 PreApplicationStartMethod?
我注意到,當我將 NuGet 中的 StructureMap 安裝到我的 ASP.NET MVC3 項目中時,Dave Ebbo 的WebActivator包也被添加為依賴項。
WebActivator 提供了一個
PreApplicationStartMethod屬性,在安裝時添加的樣板程式碼中,它用於在它自己的類中初始化 IoC 容器和依賴解析器,而不是在Global.asax’sApplication_Start方法中執行此操作。鑑於 ASP.NET 4 已經有了自己的版本,
System.Web.PreApplicationStartMethodAttribute為什麼 WebActivator 需要提供自己的版本並讓 StructureMap 使用它?我猜我不必使用WebActivator 的變體?
為達林添加程式碼:
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)); } } }
ASP.NET MVC 3 中 DI 容器的 NuGet 包通常更喜歡使用 WebActivator 以避免與
Application_Start. Ninject 使用完全相同的方法。
WebActivator.PreApplicationStartMethod您可以在應用程序中有多個屬性,在 .NET 4.5之前可以有一個System.Web.PreApplicationStartMethodAttribute.