一起谈.NET技术,ASP.NET MVC3 让依赖注入来的更简单(新补充了Ninject示例)

本文介绍了ASP.NET MVC3 Beta版中对依赖注入的支持,并通过示例展示了如何使用IDependencyResolver接口进行依赖注入。文章还提供了一个简单的实现示例,包括实现依赖注入接口的代码、全局静态类中设置依赖注入解析器的方法、控制器代码以及相关接口和类的定义。此外,文章指出了MVC框架在依赖注入方面的持续改进和变化。

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

  昨天,我写了一篇文章(参见:ASP.NET MVC 依赖注入),这种实现方式我个人一直感觉不太顺,在写出来与大家一起分享的同时,

  也是想让大家提提自己的建议, 今天下载了微软发布的最新的 ASP.NET MVC3 Beta 版,同时也仔细阅读了它的 Release Notes,

  让我感觉到惊喜的是,MVC3增加了对依赖注入的支持,增加了一  个 IDependencyResolver 接口定义,真的是很不错,比起我原来的实现要顺畅很多,

  还是老方法,上微软牛人们的博客逛一圈看看有没有已经写好的代码,有就拿来用之,没有就只能自己写了,结果让我很失望,也可能是我太笨,

  我没有找到一个完整的示例,只有一些代码片断,于是,我将其整理了一翻,也有一点点个人的心得,拿出来,与大家分享一下,

  如遇高人请不吝赐教,下面是代码片断。

  1、实现 MVC3 Beta 中提供的依赖注入接口 IDependencyResolverMyDependencyResolver.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)在自己的博客中也多次提到:

 【原文链接】:http://bradwilson.typepad.com/blog/2010/10/service-location-pt5-idependencyresolver.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值