Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a session wrapper for replacing direct call to session variables

I use a session wrapper like this:

public interface ISessionWrapper
{
   // ...
   CultureInfo Culture { get; set; }
}

public class SessionWrapper: ISessionWrapper
{
    private T GetFromSession<T>(string key)
    {
        return (T)HttpContext.Current.Session[key];
    }

    private void SetInSession(string key, object value)
    {
        HttpContext.Current.Session[key] = value;
    }

    // ...

    public CultureInfo Culture
    {
        get { return GetFromSession<CultureInfo>("Culture"); }
        set { SetInSession("Culture", value); }
    }
}

I can use this interface in my controller like this:

private readonly ISessionWrapper sessionWrapper = new SessionWrapper();
// ...
ci = new CultureInfo(langName);
sessionWrapper.Culture = ci;

But how can I access this wrapper in the view below to replace the (direct call to) session variable?

@switch (Session["Culture"].ToString()) 
{    
    case "fr":  
        // ...

    case "uk":  
        // ...
}
like image 407
Bronzato Avatar asked Jan 30 '26 02:01

Bronzato


1 Answers

You could make use of the base view:

public abstract class BaseViewPage : WebViewPage
{
    public virtual ISessionWrapper SessionWrapper
    {
        get
        {
            return new SessionWrapper();
        }
    }
}

public abstract class BaseViewPage<TModel> : WebViewPage<TModel>
{
    public virtual ISessionWrapper SessionWrapper
    {
        get
        {
            return new SessionWrapper();
        }
    }
}

your views will have access to SessionWrapper property.

Make sure to add pageBaseType="SessionWrapper" attribute to pages tag in web.config.

like image 154
Dzendo Avatar answered Feb 01 '26 18:02

Dzendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!