在Global.asax中创建一个绑定依赖于HttpContext的Ninject内核
问题描述:
创建我的内核时,我不断收到一个错误“System.Web.HttpException:请求在此上下文中不可用”。考虑到我的一个绑定依赖于上下文,这是有道理的。 Application_Start显然没有上下文。我只是想知道如果有人知道如何解决这个问题。在Global.asax中创建一个绑定依赖于HttpContext的Ninject内核
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();
}
}
答
做你想,从Business
层访问HttpContext
是好主意吗?也许你可以花一些时间重构?例如,像this之类的东西。
从应用的角度来看,你可以做这样的事情:
private void RegisterDependencyResolver()
{
kernel
.Bind<ISession>()
.To<SessionService>()
.InRequestScope()
.WithConstructorArgument(
"context",
ninjectContext => new HttpContextWrapper(HttpContext.Current)
);
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}
+0
不确定为什么这是downvoted,但这是解决这个问题的正确方法。您不希望业务层中存在具体的依赖关系。创建一个抽象! – 2015-02-26 16:14:24
我不会做一个出来的依赖的'HttpContext',只是当你设置一个变量包含注入的服务,我会再转让'HttpContext'属性。只是因为它让生活变得更容易。 – 2015-02-23 16:13:23