【问题标题】:Ninject with InRequestScope binding returning a unique item on each callNinject 与 InRequestScope 绑定在每次调用时返回一个唯一项
【发布时间】:2012-07-27 14:02:04
【问题描述】:

我在 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>();

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

任何关于我做错了什么的指针?

【问题讨论】:

    标签: c# ninject webforms


    【解决方案1】:

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

    【讨论】:

    • 我从我的解决方案中删除了所有 Ninject 包,然后添加了 Ninject.Web。然后我注意到我的 App_Start 中有两个文件,添加绑定后一切正常。
    • @WouterdeKort 我的应用程序也遇到了同样的问题,我什至创建了一个新的 WebForms 应用程序并添加了 NinjectNinject.Web.CommonNinject.Web.Common.WebHost,仍然是我的 InRequestScope 绑定都是独一无二的。 App_Start 中的“两个文件”是什么? Ninject 只添加了一个:NinjectWebCommon.cs(在旧版本中它曾经被称为 Ninject.Web.Common.cs)。谢谢
    • @ChrisWalsh 对不起,这个问题是 8 年前的问题,我不记得这两个文件在哪里了。
    • @WouterdeKort 因此,出于某种原因,InRequestScope 仅在使用公共属性上的[Inject] 属性注入时才有效,而当我直接从内核请求服务时无效。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 2013-12-27
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    相关资源
    最近更新 更多