Ninject 依赖注入

1.绑定

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EssentialTools.Models;
using Ninject;
using Ninject.Web.Common;
namespace EssentialTools.Infrastructure
{
public class NinjectDependencyResolver : IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel kernelParam)
{
kernel = kernelParam;
Bindings();//在实例化时,设置接口与类的绑定关系,这样在使用接口时就会自动关联具体类了
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}

public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
private void Bindings()
{
kernel.Bind<IValueCalculator>().To<LinqValueCalculator>().InSingletonScope(); //绑定的依赖项存放在依赖项列表中
kernel.Bind<IDiscountHelper>().To<Discount>().WithConstructorArgument("discountSizeParam", 50M);
kernel.Bind<IDiscountHelper>().To<FlexiableDiscountHelper>().WhenInjectedInto<LinqValueCalculator>();

//kernel.Bind<IInterface>().To<ImpClass>().WhenInjectedInto<T>() WhenInjectInto<T> 当要被注入的类时类型T时,实施绑定
//WhenClassHas<T> 当被注入的类以注解属性进行注释,而且类型为T时,实施绑定
//when(谓词) 当谓词(一个lambda表达式)的结果为true时实施绑定


}
}
}

Ninject作用域方法:

InTransientScope() 与未指定作用域效果相同,为每一个被解析的依赖项创建一个新的对象(每个依赖项一个实例)

InSingletonScope 创建一个单一实例,使其共享于整个应用程序。如果使用InSingletonScope,或者ToConstant(object) 为Ninject提供ToConstant方法,Ninject便会创建这种实例(每个应用一个实例)

InThreadScope() 创建一个单一实例,将其用于解析一个线程中各个对象的依赖项(每线程一个实例)

InRequestScope() 创建一个单一实例,用于解析一个Http请求中各个对象的依赖项(每个请求一个实例)

原文地址:https://www.cnblogs.com/sundh1981/p/13521730.html