3

我有一个简单的问题,我只想将一个HttpSessionStateBase对象注入到我的类中,这样它就可以测试了。由于 与HttpSessionStateBase相关HttpContextBase,并且每个 Web 请求都应该更改它,所以我用它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.

即使我删除了“会话”构造函数 arg,只留下了“测试”属性,我仍然会出现这样的错误!

4

1 回答 1

3

问题是HttpSessionState不继承自HttpSessionStateBaseHttpSessionStateBase是来自 ASP MVC 的新概念 - 更多信息在这里:为什么 ASP.NET 中有两种不兼容的会话状态类型?

尝试HttpContex.Current.Session包装HttpSessionStateWrapper

.WithConstructorArgument("session", x => HttpContext.Current == null ? 
                                                                null : 
                                                                new HttpSessionStateWrapper(HttpContext.Current.Session));
于 2013-06-10T07:02:54.477 回答