ASP.NET MVC 3讓依賴注入實(shí)現(xiàn)得更簡單
昨天,我寫了一篇文章(參見:ASP.NET MVC 依賴注入),這種實(shí)現(xiàn)方式我個人一直感覺不太順,在寫出來與大家一起分享的同時,
也是想讓大家提提自己的建議, 今天下載了微軟發(fā)布的***的ASP.NET MVC3 Beta版,同時也仔細(xì)閱讀了它的 Release Notes,
讓我感覺到驚喜的是,MVC3增加了對依賴注入的支持,增加了一個 IDependencyResolver 接口定義,真的是很不錯,比起我原來的實(shí)現(xiàn)要順暢很多,
還是老方法,上微軟牛人們的博客逛一圈看看有沒有已經(jīng)寫好的代碼,有就拿來用之,沒有就只能自己寫了,結(jié)果讓我很失望,也可能是我太笨,
我沒有找到一個完整的示例,只有一些代碼片斷,于是,我將其整理了一翻,也有一點(diǎn)點(diǎn)個人的心得,拿出來,與大家分享一下,
如遇高人請不吝賜教,下面是代碼片斷。
1、實(shí)現(xiàn) MVC3 Beta 中提供的依賴注入接口 IDependencyResolver ,MyDependencyResolver.cs 的代碼:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using Microsoft.Practices.Unity;
- namespace Demo
- {
- public class MyDependencyResolver : IDependencyResolver
- {
- #region IDependencyResolver 成員
- /// <summary>
- /// 依賴注入容器
- /// </summary>
- private UnityContainer _unityContainer;
- /// <summary>
- /// 構(gòu)造
- /// </summary>
- /// <param name="aUnityContainer">依賴注入容器</param>
- public MyDependencyResolver( UnityContainer aUnityContainer )
- {
- _unityContainer = aUnityContainer;
- }
- public object GetService( Type aServiceType )
- {
- try
- {
- return _unityContainer.Resolve( aServiceType );
- }
- catch
- {
- /// 按微軟的要求,此方法,在沒有解析到任何對象的情況下,必須返回 null,必須這么做?。。?!
- return null;
- }
- }
- public IEnumerable<object> GetServices( Type aServiceType )
- {
- try
- {
- return _unityContainer.ResolveAll( aServiceType );
- }
- catch
- {
- /// 按微軟的要求,此方法,在沒有解析到任何對象的情況下,必須返回空集合,必須這么做!?。?!
- return new List<object>( );
- }
- }
- #endregion
- }
- }
2、在 Global.asax.cs 中設(shè)置依賴注入解析器 DependencyResolver (這是一個全局靜態(tài)類,也是 MVC3 Beta 新增的):
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
- using Microsoft.Practices.Unity;
- namespace Demo
- {
- // Note: For instructions on enabling IIS6 or IIS7 classic mode,
- // visit http://go.microsoft.com/?LinkId=9394801
- public class MvcApplication : System.Web.HttpApplication
- {
- public static void RegisterGlobalFilters( GlobalFilterCollection filters )
- {
- filters.Add( new HandleErrorAttribute( ) );
- }
- public static void RegisterRoutes( RouteCollection routes )
- {
- routes.IgnoreRoute( "{resource}.axd/{*pathInfo}" );
- routes.MapRoute(
- "Default", // Route name
- "{controller}/{action}/{id}", // URL with parameters
- new { controller = "Home", action = "Index", id = UrlParameter.Optional }
- );
- }
- protected void Application_Start( )
- {
- AreaRegistration.RegisterAllAreas( );
- RegisterGlobalFilters( GlobalFilters.Filters );
- RegisterRoutes( RouteTable.Routes );
- //設(shè)置依賴注入
- RegisterDependency( );
- }
- private static UnityContainer _Container;
- public static UnityContainer Container
- {
- get
- {
- if ( _Container == null )
- {
- _Container = new UnityContainer( );
- }
- return _Container;
- }
- }
- protected void RegisterDependency( )
- {
- Container.RegisterType<ITest, Test>( );
- DependencyResolver.SetResolver( new MyDependencyResolver( Container ) );
- }
- }
- }
3、Controller的代碼,HomeController.cs:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using Microsoft.Practices.Unity;
- namespace Demo.Controllers
- {
- public class HomeController : Controller
- {
- [Dependency]
- public ITest Test { get; set; }
- public ActionResult Index( )
- {
- ViewModel.Message = Test.GetString( );
- return View( );
- }
- public ActionResult About( )
- {
- return View( );
- }
- }
- }
4、ITest.cs代碼:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Demo
- {
- public interface ITest
- {
- string GetString( );
- }
- }
5、Test.cs代碼:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace Demo
- {
- public class Test:ITest
- {
- #region ITest 成員
- public string GetString( )
- {
- return "Run demo!";
- }
- #endregion
- }
- }
***** 注意,這篇文章只適用于 ASP.NET MVC3 Beta 版,將來正式版出來了,未必采用這種方式來實(shí)現(xiàn),畢竟對于依賴注入這塊,
從 MVC1 -> MVC3 Preview1 -> MVC3 Beta 一直都在變化,微軟牛人(Brad Wilson)在自己的博客中也多次提到:
Disclaimer
This blog post talks about ASP.NET MVC 3 Beta, which is a pre-release version. Specific technical details may change before the final release of MVC 3.
This release is designed to elicit feedback on features with enough time to make meaningful changes before MVC 3 ships,
so please comment on this blog post or contact me if you have comments.
原文標(biāo)題:ASP.NET MVC3 讓依賴注入來的更簡單(新補(bǔ)充了Ninject示例)
鏈接:http://www.cnblogs.com/cnmaxu/archive/2010/10/13/1849972.html
【編輯推薦】