C# InRequestScope绑定的Ninject在每次调用时返回唯一项
我正在WebForms应用程序中使用Ninject。我为应用程序的不同部分提供了配置模块 所有绑定都设置为“InRequestScope”绑定。但是,在运行应用程序时,每次调用C# InRequestScope绑定的Ninject在每次调用时返回唯一项,c#,ninject,webforms,C#,Ninject,Webforms,我正在WebForms应用程序中使用Ninject。我为应用程序的不同部分提供了配置模块 所有绑定都设置为“InRequestScope”绑定。但是,在运行应用程序时,每次调用Kernel.Get()都会返回一个新实例 我正在Global.asax中使用以下代码: public class Global : NinjectHttpApplication { public static IKernel SharedKernel { get; private set; } protec
Kernel.Get()
都会返回一个新实例
我正在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;
}
}
公共类全局:NinjectHttpApplication
{
公共静态IKernel SharedKernel{get;private set;}
受保护的重写Ninject.IKernel CreateKernel()
{
SharedKernel=新标准内核();
//我添加了这两行来解决关于IntPtr的异常
SharedKernel.Bind().ToMethod(ctx=>()=>newbootstrapper().Kernel);
SharedKernel.Bind().To();
Load(新的NinjectDataLayerConfiguration());
返回SharedKernel;
}
}
我的模块:
public class NinjectDataLayerConfiguration : NinjectModule
{
public override void Load()
{
Bind<EFContext>().ToSelf().InRequestScope();
Bind<IProjectRepository>().To<ProjectRepository>().InRequestScope();
/* other repositories */
}
}
公共类NinjectDataLayerConfiguration:NinjectModule
{
公共覆盖无效负载()
{
Bind().ToSelf().InRequestScope();
Bind().To().InRequestScope();
/*其他存储库*/
}
}
在Web.Config中,我添加了一个HttpModule,以确保在请求结束时处理项目:
<add name="OnePerRequestModule" type="Ninject.OnePerRequestModule" />
但当我运行以下代码时:
var ProjectRepository1 = SharedKernel.Get<IProjectRepository>();
var ProjectRepository2 = SharedKernel.Get<IProjectRepository>();
var ProjectRepository1=SharedKernel.Get();
var ProjectRepository2=SharedKernel.Get();
我得到了两个不同的实例,这导致了各种各样的错误(因为我使用的是实体框架,我的ObjectContext应该通过请求共享)
有没有关于我做错了什么的提示?很可能您没有使用某个web扩展。e、 g.Ninject.Web(除了Ninject.Web.Common)对于WebForms,我从解决方案中删除了所有的Ninject包,然后添加了Ninject.Web。然后我注意到我的应用程序中有两个文件。\u Start,添加绑定后一切正常。@WouterdeKort我的应用程序也有同样的问题,我甚至创建了一个新的WebForms应用程序并添加了
Ninject
,Ninject.Web.Common
和Ninject.Web.Common.WebHost
以及我的InRequestScope
绑定都是唯一的。您在App\u Start
中的“两个文件”是什么Ninject
只向我添加了一个:NinjectWebCommon.cs
(在旧版本中,它以前被称为Ninject.Web.Common.cs
)。Thanks@ChrisWalsh很抱歉,这个问题是大约8年前提出的,我再也记不起这两个文件在哪里了。@WouterdeKort因此,出于某种原因,InRequestScope
仅在使用公共属性上的[Inject]
属性进行注入时有效,而不是在我直接从内核请求服务时有效。谢谢