ASP.NET MVC3 + Ninject.Mvc3 依赖注入原来可以这么简单

第一步、新创建一个 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 { get; set; }

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

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

}
}

原文:http://www.cnblogs.com/cnmaxu/archive/2011/10/25/2224375.html



posted @ 2012-03-01 22:11  疯长的胡茬  阅读(453)  评论(1编辑  收藏  举报