WebForms アプリケーションで Ninject を使用しています。アプリケーションのさまざまな部分に NinjectConfiguration モジュールがあります。
すべてのバインディングは「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 に HttpModule を追加して、リクエストの最後にアイテムが確実に破棄されるようにしました。
<add name="OnePerRequestModule" type="Ninject.OnePerRequestModule" />
しかし、次のコードを実行すると:
var ProjectRepository1 = SharedKernel.Get<IProjectRepository>();
var ProjectRepository2 = SharedKernel.Get<IProjectRepository>();
2 つの異なるインスタンスが返されましたが、これがあらゆる種類のエラーを引き起こしています (Entity Framework を使用しており、ObjectContext をリクエストを通じて共有する必要があるため)。
私が間違っていることについての指針はありますか?