Reputation: 33
I have a simple problem, that I just want to inject a HttpSessionStateBase
object into my class, so it can be testable.
Since the HttpSessionStateBase
is related to HttpContextBase
, and It should be changed every per web request, so I use InRequestScope()
to scope the object.
Here's my module definition:
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");
}
}
and here is the SessionManager
class:
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";
}
It is simple, but when start the project, it just throw the exception below:
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.
Even if I remove the "session" contructor arg, just left "test" property, I still error like this !
Upvotes: 3
Views: 2112
Reputation: 5666
The problem is that HttpSessionState
does not inhertis from HttpSessionStateBase
. HttpSessionStateBase
is new concept from ASP MVC - more info here: Why are there two incompatible session state types in ASP.NET?
Try to wrap HttpContex.Current.Session
with HttpSessionStateWrapper
:
.WithConstructorArgument("session", x => HttpContext.Current == null ?
null :
new HttpSessionStateWrapper(HttpContext.Current.Session));
Upvotes: 3