Unity.mvc5-正在注册会话对象
本文关键字:会话 对象 注册 mvc5- Unity | 更新日期: 2023-09-27 18:27:45
我有一个ISessionState接口
public interface ISessionState
{
void Clear();
void Delete(string key);
object Get(string key);
T Get<T>(string key) where T : class;
ISessionState Store(string key, object value);
}
和SessionState类:
public class SessionState : ISessionState
{
private readonly HttpSessionStateBase _session;
public SessionState(HttpSessionStateBase session)
{
_session = session;
}
public void Clear()
{
_session.RemoveAll();
}
public void Delete(string key)
{
_session.Remove(key);
}
public object Get(string key)
{
return _session[key];
}
public T Get<T>(string key) where T : class
{
return _session[key] as T;
}
public ISessionState Store(string key, object value)
{
_session[key] = value;
return this;
}
}
a BaseController类:
public class BaseController : Controller
{
private readonly ISessionState _sessionState;
protected BaseController(ISessionState sessionState)
{
_sessionState = sessionState;
}
internal protected ISessionState SessionState
{
get { return _sessionState; }
}
}
和用户控制器:
public class UserController : BaseController
{
public UserController(ISessionState sessionState) : base(sessionState) { }
public ActionResult Index()
{
// clear the session and add some data
SessionState.Clear();
SessionState.Store("key", "some value");
return View();
}
}
我使用Unity进行依赖项注入。本次注册:
container.RegisterType<ISessionState, SessionState>();
或
container.RegisterType<ISessionState, SessionState>(new InjectionConstructor(new ResolvedParameter<HttpSessionStateBase>("session")));
结果:当前类型System.Web.HttpSessionStateBase是一个抽象类,无法构造。您是否缺少类型映射?
在unity.mvc5注册的正确解决方案是什么?
解决此问题的一种方法是像这样注册HttpSessionStateBase
:
container.RegisterType<HttpSessionStateBase>(
new InjectionFactory(x =>
new HttpSessionStateWrapper(System.Web.HttpContext.Current.Session)));
这将提供基于当前web请求的会话,我认为这正是您想要的。