Andre DeMattia Andre DeMattia - 3 months ago 28
C# Question

convert InstanceContextMode.Single to InstanceContextMode.PerCall

I have a WCF service that takes 5 min to load everything from a database. I want to get the best performance out of WCF and found this article http://theburningmonk.com/2010/05/wcf-improve-performance-with-greater-concurrency/
it states i will get better performance using PerCall. I have anywhere between 2000 and 4000 hits per second.

my problem is it takes a long time to load the data. per the article it's saying create a wrapper to the real service using a static variable.
i am not sure how that looks and i have no idea what _container really is.
Any chance someone can give me a full example of the below?


In cases where the initialization steps are lengthy and unavoidable, or your class require a number of parameters in the constructor (for instance, when you programmatically host a service retrieve from an IoC container) the parameterless constructor can become a problem. To get around this, you could create a wrapper for your class and expose the wrapper as the service instead but hold a static instance of the underlying service which all the requests are passed on to:


[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyServiceWrapper : IMyServiceWrapper
{
// get the underlying service from the container
private static IMyService MyService = _container.Resolve<IMyService>();


public MyServiceWrapper()
{
// parameterless constructor which does nothing, so easy to constructor
}
public void DoSomething()
{
MyService.DoSomething();
}


}

// dummy interface to ensure the wrapper has the same methods as the underlying service
// but helps to avoid confusion
public interface IMyServiceWrapper : IMyService
{
}



For a sessionful service, the PerSession instance context mode gives
you all the benefit of the PerCall instance context mode and at the
same time reduces the overhead you pay for that extra concurrency
because new instances of your class are no longer created for each
request but for each session instead.

Answer

You can remove the logic of fetching service object from IOC container:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class MyServiceWrapper : IMyServiceWrapper
    {
        // get the underlying service from the container
        private static IMyService myService = new MyService();


        public MyServiceWrapper()
        {
            // parameterless constructor which does nothing, so easy to constructor
        }
        public void DoSomething()
        {
            myService.DoSomething();
        }
    }

    // dummy interface to ensure the wrapper has the same methods as the underlying service
    // but helps to avoid confusion
    public interface IMyServiceWrapper : IMyService
    {
    }