2012-07-27 76 views
1

我在WebForms應用程序中使用Ninject。我有用於應用程序不同部分的NinjectConfiguration模塊。Ninject使用InRequestScope綁定在每次調用時返回一個唯一項目

所有綁定都設置爲'InRequestScope'綁定。但是,運行應用程序時,每次調用Kernel.Get<T>()都會返回一個新實例。

我用我的Global.asax下面的代碼:

public class Global : NinjectHttpApplication 
{ 
    public static IKernel SharedKernel { get; private set; } 

    protected override Ninject.IKernel CreateKernel() 
    { 
     SharedKernel = new StandardKernel(); 

     // I have added these two lines to resolve an exception about IntPtr 
     SharedKernel.Bind<Func<IKernel>>().ToMethod(ctx =>() => new Bootstrapper().Kernel); 
     SharedKernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); 

     SharedKernel.Load(new NinjectDataLayerConfiguration()); 

     return SharedKernel; 
    } 
} 

我NinjectModule:

public class NinjectDataLayerConfiguration : NinjectModule 
{ 
    public override void Load() 
    { 
     Bind<EFContext>().ToSelf().InRequestScope(); 
     Bind<IProjectRepository>().To<ProjectRepository>().InRequestScope(); 

     /* other repositories */ 
    } 
} 

而且Web.Config中我添加了一個HTTP模塊,以確保項目處置在請求的末尾:

<add name="OnePerRequestModule" type="Ninject.OnePerRequestModule" /> 

但是當我運行下面的代碼:

var ProjectRepository1 = SharedKernel.Get<IProjectRepository>(); 
var ProjectRepository2 = SharedKernel.Get<IProjectRepository>(); 

我得到兩個不同的實例,這導致所有類型的錯誤(因爲我使用實體框架和我的ObjectContext應通過請求共享)。

我做錯了什麼指針?

回答

1

很有可能你不使用網絡擴展之一。例如Ninject.Web(除了Ninject.Web.Common)在WebForms的情況下

+0

我從我的解決方案中刪除所有Ninject包,然後添加Ninject.Web。然後我注意到我的App_Start中有兩個文件,並且在添加了所有工作的綁定之後。 – 2012-07-30 08:03:13

相關問題