无法让DependencyResolver与ninject一起使用?

时间:2011-09-19 01:46:29

标签: asp.net-mvc-3 ninject

我在Ninject的bootstap中有这个代码:

private static IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    RegisterServices(kernel);
    DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
    return kernel;
}

private static void RegisterServices(IKernel kernel)
{
    //TODO: Enregistrer les services ici.. pour ninject!
    kernel.Bind<IContext>().To<MySampleContext>();
    kernel.Bind<ISampleService>().To<SampleService>();
}  

在我的全球范围内,我试试这个..

 protected virtual void Application_BeginRequest()
        {
            ContextProvider cp = new ContextProvider();
            DbContext context = (DbContext)DependencyResolver.Current.GetService<IContext>();
            cp.SetCurrent(context);
        }

编辑:这里是完整的引导程序......但它是ninjectt附带的基本引导程序。

public static class NinjectMVC3 
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    public static void Start() 
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
        DynamicModuleUtility.RegisterModule(typeof(HttpApplicationInitializationModule));
        bootstrapper.Initialize(CreateKernel);
    }

    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        RegisterServices(kernel);
        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
        return kernel;
    }

    private static void RegisterServices(IKernel kernel)
    {
        //TODO: Enregistrer les services ici.. pour ninject!
        kernel.Bind<IContext>().To<MySampleContext>();
        kernel.Bind<ISampleService>().To<SampleService>();
    }        
}

但它返回NULL?为什么?

1 个答案:

答案 0 :(得分:3)

使用NuGet上的Ninject.MVC3并阅读文档https://github.com/ninject/ninject.web.mvc/wiki/MVC3