asp.net mvc和webapi试用ninject依赖注入
学习asp.net的过程中看了《精通ASP.NET MVC5》其中依赖注入使用了ninject。笔者使用的3.0版本。具体实现如下:
第一步:在nuget里面添加后会自动在APP_Start里面生成NinjetWebCommon.cs文件。
NinjectWebCommon[assembly: WebActivator.PreApplicationStartMethod(typeof(SportStore.WebUI.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(SportStore.WebUI.App_Start.NinjectWebCommon), "Stop")]
namespace SportStore.WebUI.App_Start
{
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using Ninject.Web.Common.WebHost;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
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();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
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)
{
System.Web.Mvc.DependencyResolver.SetResolver(new SportStore.WebUI.Infrastructure.NinjectDependencyResolver(kernel));
}
}
}
第二步我们需要实现依赖解析接口 :创建NinjectDependencyResolver.cs文件,实现IDependencyResolver。并在NinjetWebCommon文件里面注册就可以快乐的binding了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ninject;
using System.Web.Mvc;
using Ninject.Web.Common;
using Moq;
using SportStore.Domain.Entities;
using SportStore.Domain.Abstract;
using SportStore.Domain.Concreate;
using System.Configuration;
using SportStore.WebUI.Infrastructure.Abstract;
using SportStore.WebUI.Infrastructure.Concrete;
namespace SportStore.WebUI.Infrastructure
{
public class NinjectDependencyResolver : IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel kernekParam )
{
kernel = kernekParam;
AddBindings();
}
public object GetService( Type serviceType )
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices( Type serviceType )
{
return kernel.GetAll(serviceType);
}
private void AddBindings()
{
//Mock<IProductsRepository> mock = new Mock<IProductsRepository>();
//mock.Setup(m => m.Products).Returns(new List<Product>
//{
// new Product {Name="FootBALL",Price=25 ,Description="Nike"},
// new Product {Name="Surf board",Price=179 },
// new Product {Name="Running shoes",Price=95 }
//});
kernel.Bind<IProductsRepository>().To<EFProductRepository>();
EmailSettings emailSettings = new EmailSettings
{
WriteAsFile = bool.Parse(ConfigurationManager.AppSettings["Email.WriteAsFile"] ?? "false")
};
kernel.Bind<IOrderProcessor>().To<EmailOrderProcessor>().WithConstructorArgument("settings", emailSettings);
kernel.Bind<IAuthProvider>().To<FormsAuthProvider>();
}
}
}
然而在使用最新版本时,发现并不会自动生成NinjetWebCommon文件。当然我们可以用旧版的文件修改实现。后来去git查找发现并不需要这么麻烦了。直接继承NinjectHttpApplication。实现抽象类里面的CreateKernel()就可以更快乐的bind了。