2015-12-21 101 views
1

我有一個ISessionState接口Unity.mvc5 - 註冊會話對象

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

一個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註冊的正確解決方案是什麼?解決這個問題

回答

1

一種方式是註冊HttpSessionStateBase這樣的:

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

這將根據當前Web請求,我以爲是你想要的東西提供了會議。

+0

它是一個很好的解決方案。我設法用Castle.Core nuget解決它,但這更清楚。謝謝! –