15
2011

IOC框架实践之Ninject

1.   入门

1.1.  面向接口

public interface IWeapon
{
    void Attack(string target);
}
public class Sword : IWeapon
{
    public void Attack(string target)
    {
        Console.WriteLine("Attack " + target + " by sword");
    }
}
public class Knife : IWeapon
{
    public void Attack(string target)
    {
        Console.WriteLine("Attack " + target + " by knife");
    }
}

1.2.  类型绑定

public class WeaponModule : NinjectModule
{
    public override void Load()
    {
        this.Bind().To();
    }
}

1.3.  简单应用

static void Main(string[] args)
{
    IKernel kernel = new StandardKernel(new WeaponModule());
    IWeapon weapon = kernel.Get();
    weapon.Attack("小明");
    Console.ReadKey();
}

2.   进阶

2.1.  对象作用域

作用域

绑定方法

说明

Transient

.InTransientScope()

每次调用创建新实例。

Singleton

.InSingletonScope()

单例,仅创建一个实例。

Thread

.InThreadScope()

每一个线程创建一个实例。

Request

.InRequestScope()

每当Web请求发起时创建一个实例,结束请求时释放实例。

 

2.2.  复杂绑定处理

this.Bind().To().Named("Sword");
this.Bind().To().Named("Knife");
IWeapon weapon1 = kernel.Get("Sword");
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.  动态载入模块

IKernel kernel = new StandardKernel();
kernel.Load(AppDomain.CurrentDomain.GetAssemblies());

注:需要引入CommonServiceLocator.NinjectAdapter.dll

3.2.  扩展Asp.Net MVC

// 重写ControllerFactory
public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel _kernel = new StandardKernel(new PersonModule());
    protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null) return null;
        return (IController)_kernel.Get(controllerType);
    }
}

// 重新设置ControllerFactory
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    // 设置ControllerFactory为NinjectControllerFactory
    ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
}

示例下载: NinjectDemo.zip

相关日志

4 条评论 + 发条评论

  • 写的不错

  • 你不是要考研吗?怎么有时间研究这些?

    • 不考研啦~呵呵~

      • 那你签了工作没?

发条评论

*

*

注意: 评论者允许使用'@user空格'的方式将自己的评论通知另外评论者。例如, ABC是本文的评论者之一,则使用'@ABC '(不包括单引号)将会自动将您的评论发送给ABC。使用'@all ',将会将评论发送给之前所有其它评论者。请务必注意user必须和评论者名相匹配(大小写一致)。