Ninject:WithConstructorArgument和WithPropertyValue不起作用

时间:2013-06-08 03:11:35

标签: c# ninject

我有一个简单的问题,我只想在我的类中注入一个HttpSessionStateBase对象,因此它可以测试。 由于HttpSessionStateBaseHttpContextBase相关,因此每个网络请求都应更改一次,因此我使用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”属性,我仍然会这样出错!

1 个答案:

答案 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));