5

I'm adding some tests to a class that uses HttpContext.Current.Session internally and we are porting to ASP.NET MVC. My class looks like this:

class Foo
{
    public void foo()
    {
        HttpContext.Current.Session["foo"] = "foo";
    }
}

I thought to change it like this:

class Foo
{
    IHttpSessionState session;

    public Foo() : this(HttpContext.Current.Session) {}

    public Foo(IHttpSessionState session)
    {
        m_session = session;
    }

    public void foo()
    {
        m_session["foo"] = "foo";
    }
}

The problem is with the default constructor. I can't pass the old classes since they don't implement the new ASP.NET MVC interfaces.

Is there anyway to obtain the instances that implement IHttpSessionState in the default constructor?

Thanks

1 Answer 1

5

Try this, it used the IHttpSessionState wrapper that the MVC framework uses.

class Foo
{
    // member variable set by constructor
    IHttpSessionState m_session;

    // if no session is passed it attempts to create a new session state wrapper from the current session
    public Foo() : this(new HttpSessionStateWrapper(HttpContext.Current.Session)) {}

    public Foo(IHttpSessionState session)
    {
        m_session = session;
    }

    public void foo()
    {
        m_session["foo"] = "foo";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.