我有一个简单的问题,我只想在我的类中注入一个HttpSessionStateBase
对象,因此它可以测试。
由于HttpSessionStateBase
与HttpContextBase
相关,因此每个网络请求都应更改一次,因此我使用InRequestScope()
来确定对象的范围。
这是我的模块定义:
public class WebBusinessModule : NinjectModule
{
public override void Load()
{
this.Bind<CartManager>().ToSelf().InSingletonScope();
this.Bind<ISessionManager>().To<SessionManager>().InRequestScope()
.WithConstructorArgument("session", ctx => HttpContext.Current == null ? null : HttpContext.Current.Session)
.WithPropertyValue("test", "test");
}
}
这是SessionManager
类:
public class SessionManager : ISessionManager
{
[Inject]
public SessionManager(HttpSessionStateBase session)
{
this.session = session;
}
public SessionModel GetSessionModel()
{
SessionModel sessionModel = null;
if (session[SESSION_ID] == null)
{
sessionModel = new SessionModel();
session[SESSION_ID] = sessionModel;
}
return (SessionModel)session[SESSION_ID];
}
public void ClearSession()
{
HttpContext.Current.Session.Remove(SESSION_ID);
}
private HttpSessionStateBase session;
[Inject]
public string test { get; set; }
private static readonly string SESSION_ID = "sessionModel";
}
这很简单,但是在启动项目时,它只是抛出以下异常:
Error activating HttpSessionStateBase
No matching bindings are available, and the type is not self-bindable.
Activation path:
3) Injection of dependency HttpSessionStateBase into parameter session of constructor of type SessionManager
2) Injection of dependency SessionManager into property SessionManager of type HomeController
1) Request for HomeController
Suggestions:
1) Ensure that you have defined a binding for HttpSessionStateBase.
2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
3) Ensure you have not accidentally created more than one kernel.
4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
5) If you are using automatic module loading, ensure the search path and filters are correct.
即使我删除了“session”构造函数arg,只需要保留“test”属性,我仍然会这样出错!
答案 0 :(得分:3)
问题在于HttpSessionState
不在HttpSessionStateBase
之内。 HttpSessionStateBase
是来自ASP MVC的新概念 - 更多信息:Why are there two incompatible session state types in ASP.NET?
尝试用HttpContex.Current.Session
包裹HttpSessionStateWrapper
:
.WithConstructorArgument("session", x => HttpContext.Current == null ?
null :
new HttpSessionStateWrapper(HttpContext.Current.Session));