【问题标题】:Creating a Ninject Kernel in Global.asax where a binding has a dependency on HttpContext在 Global.asax 中创建一个 Ninject 内核,其中绑定依赖于 HttpContext
【发布时间】:2015-02-23 16:11:07
【问题描述】:

创建内核时,我不断收到错误“System.Web.HttpException:请求在此上下文中不可用”。考虑到我的一个绑定依赖于上下文,这是有道理的。显然,Application_Start 上不应存在上下文。我只是想知道是否有人知道如何解决这个问题。

public class NinjectBindings : NinjectModule
{
    public override void Load()
    {     
        //Framework
        Bind<IJsonLayer>().To<JsonLayer>();
        Bind<IBusinessLayer>().To<BusinessLayer>();

        //Controllers
        Bind<ITeamController>().To<TeamController>();
    }
}


public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        ReflectionUtility.Kernel = new StandardKernel(new NinjectBindings());
    }
}


public class ReflectionUtility
{
    private static IKernel _kernel;

    public static IKernel Kernel {
        set { _kernel = value; }
    }
}



public class JsonLayer : IJsonLayer
{
    private readonly ITeamController _teamController;
    private readonly IBusinessLayer _businessLayer;

    public JsonLayer(ITeamController teamController, IBusinessLayer businessLayer)
    {
        _teamController = teamController;
        _businessLayer = businessLayer;
    }
}


public class BusinessLayer : IBusinessLayer
{
    //this is a super-simplification of what's going on. there are multiple different calls to HttpContext.Current.Request in this class
    public BusinessLayer()
    {
         //This is where it breaks
         var sessionUserId = HttpContext.Current.Request.Headers["X-SessionUserId"];
    }

}

public class TeamController : ITeamController
{
      public void DeleteTeam(int intTeam)
      {
          throw new NotImplementedException();
      }
}

【问题讨论】:

  • 我不会从HttpContext 中建立依赖关系,只是当您设置一个包含注入服务的变量时,我会将HttpContext 分配给一个属性。只是因为它让生活更轻松。

标签: c# .net ninject global-asax httpcontext


【解决方案1】:

您认为从Business 层访问HttpContext 是个好主意吗?也许您可以花一些时间进行重构?例如,this 之类的东西。

从应用程序的角度来看,您可以这样做:

private void RegisterDependencyResolver()
{
     kernel
     .Bind<ISession>()
     .To<SessionService>()
     .InRequestScope()
     .WithConstructorArgument(
         "context", 
         ninjectContext => new HttpContextWrapper(HttpContext.Current)
      );

     DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}

【讨论】:

  • 不知道为什么这被否决了,但这是解决这个问题的正确方法。您不希望业务层中有具体的依赖关系。创建一个抽象!
猜你喜欢
  • 2016-05-23
  • 1970-01-01
  • 2015-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-21
  • 1970-01-01
  • 2020-05-30
相关资源
最近更新 更多