views:

304

answers:

3

I have a web service in C# and would like to have a nested inner class, that abstracts away the session collection, something like this:


public class Service : System.Web.Services.WebService
{
    [WebMethod]
    public string Foo(string ticket)
    {
        SessionPool.getSession(ticket);
    }

    private class SessionPool 
    {
        public static Session getSession(string ticket)
        {
            // this is what i want to do, but I can't access Context
            return (Session)Context.Session[ticket];
        }
    }
}

Is it possible to access the HTTP context of the WebService class via a nested class? If not, is there way I can store the reference to it?

A: 
System.Web.HttpContext.Current

?

cfeduke
+3  A: 

Nested classes in C# aren't like (non-static) inner classes in Java. There is no implicit reference to an instance of the containing class - so you can't use any instance members of the containing class without an explicit reference.

However, you do have access to all private members of the containing class - with a suitable reference for instance members.

Jon Skeet
A: 

I can think of a couple things.

First, you might try using getContext() instead of just accessing Context. If that works, you're done.

If not, you could pass the Service in as an initializer to your SessionPool. Add a WebService handle to SessionPool that you initialize via a call to setService() before calling getSession() from Foo().

Although, at that point, why not just pass in the Context as an argument to getSession()?

Bill James