1. 入门
1.1. 面向接口
01 | public interface IWeapon |
03 | void Attack( string target); |
05 | public class Sword : IWeapon |
07 | public void Attack( string target) |
09 | Console.WriteLine( "Attack " + target + " by sword" ); |
12 | public class Knife : IWeapon |
14 | public void Attack( string target) |
16 | Console.WriteLine( "Attack " + target + " by knife" ); |
1.2. 类型绑定
1 | public class WeaponModule : NinjectModule |
3 | public override void Load() |
1.3. 简单应用
1 | static void Main( string [] args) |
3 | IKernel kernel = new StandardKernel( new WeaponModule()); |
4 | IWeapon weapon = kernel.Get(); |
2. 进阶
2.1. 对象作用域
作用域 | 绑定方法 | 说明 |
Transient | .InTransientScope() | 每次调用创建新实例。 |
Singleton | .InSingletonScope() | 单例,仅创建一个实例。 |
Thread | .InThreadScope() | 每一个线程创建一个实例。 |
Request | .InRequestScope() | 每当Web请求发起时创建一个实例,结束请求时释放实例。 |
2.2. 复杂绑定处理
1 | this .Bind().To().Named( "Sword" ); |
2 | this .Bind().To().Named( "Knife" ); |
3 | IWeapon weapon1 = kernel.Get( "Sword" ); |
4 | IWeapon weapon2 = kernel.Get( "Knife" ); |
其他方法:https://github.com/ninject/ninject/wiki/Contextual-Binding
2.3. 对象创建过程
详见:https://github.com/ninject/ninject/wiki/The-Activation-Process
3. 扩展
3.1. 动态载入模块
1 | IKernel kernel = new StandardKernel(); |
2 | kernel.Load(AppDomain.CurrentDomain.GetAssemblies()); |
注:需要引入CommonServiceLocator.NinjectAdapter.dll
3.2. 扩展Asp.Net MVC
02 | public class NinjectControllerFactory : DefaultControllerFactory |
04 | private IKernel _kernel = new StandardKernel( new PersonModule()); |
05 | protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType) |
07 | if (controllerType == null ) return null ; |
08 | return (IController)_kernel.Get(controllerType); |
13 | protected void Application_Start() |
15 | AreaRegistration.RegisterAllAreas(); |
16 | RegisterGlobalFilters(GlobalFilters.Filters); |
17 | RegisterRoutes(RouteTable.Routes); |
19 | ControllerBuilder.Current.SetControllerFactory( new NinjectControllerFactory()); |
示例下载: NinjectDemo.zip