標籤:on() 工具 步驟 manager tor lazy pos out bubuko
ASP.NET MVC Dependency Injection
同志們,非常快速的Ioc註冊介面和注入Mvc Controller,步驟如下:
安裝Unity.Mvc NuGet Package 在你的項目中,開啟Package Manager Console進行安裝。
接下來我們可以看見兩個類檔案UnityConfig.cs 和 UnityMvcActivator.cs,介面註冊需要在UnityConfig.cs裡寫你的介面執行個體,UnityMvcActivator.cs 它會協助你自動resolver,放心吧,這個工具太無腦了,需要做的不多
1.註冊介面
public static class UnityConfig { #region Unity Container private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() => { var container = new UnityContainer(); RegisterTypes(container); return container; }); /// <summary> /// Configured Unity Container. /// </summary> public static IUnityContainer Container => container.Value; #endregion /// <summary> /// Registers the type mappings with the Unity container. /// </summary> /// <param name="container">The unity container to configure.</param> /// <remarks> /// There is no need to register concrete types such as controllers or /// API controllers (unless you want to change the defaults), as Unity /// allows resolving a concrete type even if it was not previously /// registered. /// </remarks> public static void RegisterTypes(IUnityContainer container) { // NOTE: To load from web.config uncomment the line below. // Make sure to add a Unity.Configuration to the using statements. // container.LoadConfiguration(); // TODO: Register your type‘s mappings here. // container.RegisterType<IProductRepository, ProductRepository>(); container.RegisterType<IRepository, RepositoryImpl>(); }
2.注入介面到Controller
public class HomeController : Controller { private IRepository _repository; public HomeController(IRepository repository) { _repository = repository; } public ActionResult Index() { var result = _repository.Test(); return View(result); }
}
3.啟動Ioc初始化,代碼在Global.asax
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); UnityConfig.RegisterTypes(new UnityContainer()); } }
少年F5啟動你的程式,見證奇蹟的時刻,最快速的搭建.net Mvc Ioc 介面執行個體以及Controller的依賴注入。
C# Ioc ASP.NET MVC Dependency Injection