gpt4 book ai didi

c# - Ninject:WithConstructorArgument 和 WithPropertyValue 不起作用

转载 作者:行者123 更新时间:2023-11-30 16:17:32 28 4
gpt4 key购买 nike

我有一个简单的问题,我只想将一个 HttpSessionStateBase 对象注入(inject)到我的类中,以便它可以测试。由于 HttpSessionStateBaseHttpContextBase 相关,并且每个 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.

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

最佳答案

问题是 HttpSessionState 没有继承自 HttpSessionStateBaseHttpSessionStateBase 是 ASP MVC 的新概念 - 更多信息请点击此处:Why are there two incompatible session state types in ASP.NET?

尝试用 HttpSessionStateWrapper 包装 HttpContex.Current.Session:

.WithConstructorArgument("session", x => HttpContext.Current == null ? 
null :
new HttpSessionStateWrapper(HttpContext.Current.Session));

关于c# - Ninject:WithConstructorArgument 和 WithPropertyValue 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16995658/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com