user3759078
user3759078

Reputation: 13

Singleton execution for multiple application requests with persession WCF service object

I have one class (Concurrency) object in which i am initiating all db related settings . All this code is in WCF service. For instance management, i have made service instance on persession basis. Now i want to share Concurrency class object through all db layer classes. I was thinking to do this singleton can be used.Though i have used persession instance creation for wcf service, i am confused , how singleton pattern will react for multiple requests at same time. Will each user get same class object or same class object will be shared with all users ?

Scenario is : I have user object. User belongs to organisation. WCF service have method 'UserRegistration'. with wcf service , i have separate class library for db operations. When any client calls user registration method, in Concurrency object i have to set db settings against user's organisation . For this i want to manage one Concurrency object per user. Is it right way to do?

Upvotes: 1

Views: 823

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156978

I hope understand your question correctly. I had this issue myself with a single entry point for our DAL. It had to work on multiple platforms: WCF, WF, ASMX, ASP.NET, etc.

I came up with this implementation of singleton that saves the class instance in the user session, when applicable for that platform:

public static Class1 Current
{
    get
    {
        if (HttpContext.Current != null) /* ASP.NET / ASMX / ASHX */
        {
            if (HttpContext.Current.Session["Class1"] == null)
                HttpContext.Current.Session["Class1"] = new Class1();

            return (Class1)HttpContext.Current.Session["Class1"];
        }
        else if (OperationContext.Current != null) /* WCF */
        {
            if (WcfInstanceContext.Current["Class1"] == null)
                WcfInstanceContext.Current["Class1"] = new Class1();

            return (Class1)WcfInstanceContext.Current["Class1"];
        }
        else /* WPF / WF / Single instance applications */
        {
            if (Class1.current == null)
                Class1.current = new Class1();

            return Class1.current;
        }
    }
}

If you have multiple objects in your layer, you could refactor this away in a base class or method.

Upvotes: 1

Related Questions