[转] ASP.NET MVC3 让依赖注入来的更简单(新补充了Ninject示例)

本文详细介绍了如何在ASP.NET MVC3 Beta版中使用Unity框架实现依赖注入,并提供了完整的代码示例。包括依赖注入接口IDependencyResolver的实现、全局配置、控制器使用依赖注入以及相关组件的代码实现。适合开发人员了解和实践MVC框架的依赖注入技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

转载于:https://www.cnblogs.com/RobotTech/archive/2011/07/12/2104179.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值