好久没有写文章了,懒。

今天收到一封邮件,是一位叫 HMQ 的同人,对我写过的 ASP.NET MVC3 依赖注入 的文章提出了问题,

当时我写这篇文章的时候,正式的 MVC3 版本还没有出来,当时我用的是 MVC3 Beta 版,而现在 MVC4 都快出来了,

因此这个 Demo 在当时的环境下是测试通过的,没有问题,而在现在的环境下可能会有问题(本人没有测试过),

如果哪天有时间,我会把这个 Demo 拿下来,进行适当的修改,让它适合当前的 MVC3 版本,不过话又说回来我觉得没有太大必要,

因为现在想在 ASP.NET MVC3 中使用依赖注入非常的简单,几乎用不了几行代码就可以实现依赖注入,我推荐使用 Ninject,

具体步骤如下:

 

第一步、新创建一个 ASP.NET MVC3 工程。

第二步、通过 NuGet 控制台直接输入命令:install-package Ninject.Mvc3

安装完这个源码包之后,所有的依赖注入框架已设置完成,无须你改动任何代码,

你会发现项目中添加了一个“App_Start”文件夹,在这个文件夹中生成了一个名为“NinjectMVC3.cs”的代码文件。

第三步、打开 \App_Start\NinjectMVC3.cs,找到 RegisterServices 方法,将你的依赖注入映射代码直接写入即可。

 

代码清单如下:

自动生成的 \App_Start\NinjectMVC3.cs 代码:

[assembly: WebActivator.PreApplicationStartMethod(typeof(MvcApplication3.App_Start.NinjectMVC3), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(MvcApplication3.App_Start.NinjectMVC3), "Stop")]

namespace MvcApplication3.App_Start
{
    using System.Reflection;
    using Microsoft.Web.Infrastructure.DynamicModuleHelper;
    using Ninject;
    using Ninject.Web.Mvc;
    using MvcApplication3.Services;
    {

    public static class NinjectMVC3 
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        /// <summary>
        
/// Starts the application
        
/// </summary>
        public static void Start() 
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
            DynamicModuleUtility.RegisterModule(typeof(HttpApplicationInitializationModule));
            bootstrapper.Initialize(CreateKernel);
        }
        
        /// <summary>
        
/// Stops the application.
        
/// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }
        
        /// <summary>
        
/// Creates the kernel that will manage your application.
        
/// </summary>
        
/// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            RegisterServices(kernel);
            return kernel;
        }

        /// <summary>
        
/// Load your modules or register your services here!
        
/// </summary>
        
/// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            //写入你需要绑定的依赖注入关系,除了此方法之外的其它代码都是自动生成的,无须我们操心。

            //2011-10-26 新修复 bug,遗漏了后面的 InRequestScope(),这个很重要!

            //感谢  Scott Xu 南方小鬼  的指错:),差点误人子弟啊!

 

            kernel.Bind<ITestService>().To<TestService>().InRequestScope();

        }        
    }
}

 

测试代码如下: 

\Services\ITestService.cs

namespace MvcApplication3.Services
{
    public interface ITestService
    {
        string GetMessage(string aString);
    }
} 

 

\Services\TestService.cs 

using System;

namespace MvcApplication3.Services
{
    public class TestService : ITestService
    {
        string ITestService.GetMessage(string aString)
        {
            return "--------------" + (String.IsNullOrEmpty(aString) ? String.Empty : aString) + "--------------";
        }
    }
}

 

\Controllers\HomeController.cs

using System.Web.Mvc;
using Ninject;
using MvcApplication3.Services;

namespace MvcApplication3.Controllers
{
    public class HomeController : Controller
    {

        [Inject]
        public ITestService Service { getset; }

        public ActionResult Index()
        {
            ViewBag.Message = Service.GetMessage("Welcome to ASP.NET MVC!");
            return View();
        }

        public ActionResult About()
        {
            return View();
        }

    }
}

 

在此基础上我们自己可以进行一些优化,从而使依赖注入使用起来更加方便, 更适合团队开发,

随便说一句 NuGet 真是不错,应该好好利用。

源码下载:Ninect.Mvc3_Demo.zip(环境:VS2010 SP1 + MVC3)


posted on 2011-10-25 21:51  老马快跑  阅读(5393)  评论(11编辑  收藏  举报