简体   繁体   English

在Global.asax中创建Ninject内核,其中绑定依赖于HttpContext

[英]Creating a Ninject Kernel in Global.asax where a binding has a dependency on HttpContext

I keep getting an error "System.Web.HttpException: Request is not available in this context" when creating my Kernel. 在创建内核时,我不断收到错误“System.Web.HttpException:请求在此上下文中不可用”。 Which makes sense given that one of my bindings has a dependency on the Context. 鉴于我的一个绑定依赖于Context,这是有道理的。 Obviously no context should be present on Application_Start. 显然,Application_Start上不应出现任何上下文。 I'm just wondering if anyone knows how to resolve this. 我只是想知道是否有人知道如何解决这个问题。

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();
      }
}

Do your think, that access to the HttpContext from Business layer is good idea? 您认为,从Business层访问HttpContext是个好主意吗? Maybe you can spend some time on refactoring? 也许你可以花一些时间进行重构? For example, something like this . 例如,像这样的东西。

From application perspective you can do something like this: 从应用程序的角度来看,你可以这样做:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM