Unity.mvc5 - 注册会话对象

Unity.mvc5 - Registering Session object

我有一个 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 class:

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;
    }
}

一个 BaseController class:

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 是一个抽象 class,无法构造。您是否缺少类型映射?

unity.mvc5注册的正确解决方案是什么?

解决此问题的一种方法是像这样注册 HttpSessionStateBase

container.RegisterType<HttpSessionStateBase>(
    new InjectionFactory(x =>
        new HttpSessionStateWrapper(System.Web.HttpContext.Current.Session)));

这将提供基于当前网络请求的会话,我认为这就是您想要的。