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应通过请求共享)。
我做错了什么指针?
我从我的解决方案中删除所有Ninject包,然后添加Ninject.Web。然后我注意到我的App_Start中有两个文件,并且在添加了所有工作的绑定之后。 – 2012-07-30 08:03:13