[转] ASP.NET MVC3 让依赖注入来的更简单(新补充了Ninject示例)
Links:http://www.cnblogs.com/cnmaxu/archive/2010/10/13/1849972.html
昨天,我写了一篇文章(参见:ASP.NET MVC 依赖注入),这种实现方式我个人一直感觉不太顺,在写出来与大家一起分享的同时,
也是想让大家提提自己的建议, 今天下载了微软发布的最新的 ASP.NET MVC3 Beta 版,同时也仔细阅读了它的 Release Notes,
让我感觉到惊喜的是,MVC3增加了对依赖注入的支持,增加了一个 IDependencyResolver 接口定义,真的是很不错,比起我原来的实现要顺畅很多,
还是老方法,上微软牛人们的博客逛一圈看看有没有已经写好的代码,有就拿来用之,没有就只能自己写了,结果让我很失望,也可能是我太笨,
我没有找到一个完整的示例,只有一些代码片断,于是,我将其整理了一翻,也有一点点个人的心得,拿出来,与大家分享一下,
如遇高人请不吝赐教,下面是代码片断。
1、实现 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>
/// 构造
/// </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 中设置依赖注入解析器 DependencyResolver (这是一个全局静态类,也是 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 );
//设置依赖注入
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 版,将来正式版出来了,未必采用这种方式来实现,毕竟对于依赖注入这块,
从 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.
(参见原文:http://bradwilson.typepad.com/blog/2010/10/service-location-pt5-idependencyresolver.html)
在下 e 文太差,我就不丢人了,e 文好的自己看吧。
这里是采用Unity依赖注入框架的完整示例:下载(环境:VS2010 + MVC3 Beta + Unity)
这里是采用Ninject依赖注入框架的完整示例:下载(环境:VS2010 + MVC3 Beta + Ninject)