c# - 具有 InRequestScope 绑定(bind)的 Ninject 在每次调用时返回一个唯一的项目

标签 c# ninject webforms

我在 WebForms 应用程序中使用 Ninject。我有用于应用程序不同部分的 NinjectConfiguration 模块。

所有绑定(bind)均设置为“InRequestScope”绑定(bind)。但是,运行应用程序时每次调用 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>();

我返回了两个不同的实例,这导致了各种错误(因为我使用的是 Entity Framework ,并且我的 ObjectContext 应该通过请求共享)。

有什么关于我做错了什么的指示吗?

最佳答案

您很可能不使用其中一种网络扩展程序。例如对于 WebForms,Ninject.Web(除了 Ninject.Web.Common 之外)

关于c# - 具有 InRequestScope 绑定(bind)的 Ninject 在每次调用时返回一个唯一的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11689374/

相关文章:

C# 遍历按值排序的字典

asp.net - Angular HttpClient 调用缺少查询字符串和授权 header

php - 使用 PayPal API 和 PHP 设置简单的 Retreat 注册

c# - 使用参数在 C# 中创建通用工厂

c# - 如何在混合应用程序中获取有关缓冲区溢出异常的信息?

asp.net-mvc-3 - 让 ninject/ninject.commons/ninject.web.mvc 与 Mono 2.10.x 和 ASP.NET MVC3 一起使用

c# - 使用 Ninject : Named binding or WithConstructorArgument doesn't work 进行多次注入(inject)

.net - Sys.WebForms.PageRequestManagerServerErrorException : An unknown error

c# - 何时创建新任务

c# - 使用 Ninject 开放泛型和 IEnumerable