Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static constructor called twice for PerSession WCF service

Can't udnerstand why type constructor for PerSession/ WCF service was calling twice. ConcurrencyMode is Multiple. Just launching five simultaneous clients which do the same WCF service method call, in a log I see that static constructor was called twice, the first time and after 3 seconds second time with an other ProcessId/ThreadId. No exceptions neither in constructor itself nor WCF trace logs. Constructor execution time is ~10 milliseconds as per log. This results in all static fields are not shared between all service instances as supposed and in case of 5 client connections I have 5 services and two different static contexts so change in onse static field is not reflected for all services.

This issue confuses many things since I am relying on some static caches shared across multiple service instances.

Service is hosted in IIS. No IIS restarts, AppPool recycles on this time interval.

[AspNetCompatibilityRequirements(RequirementsMode =
  AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(
  InstanceContextMode = InstanceContextMode.PerSession, 
  IncludeExceptionDetailInFaults = true, 
  ConcurrencyMode = ConcurrencyMode.Multiple)]
public class WcfService
{ 
    private static readonly ILog logger;
    private static volatile bool typeInitialized;

    static WcfService()
    {
        try
        {
            // Here is typeInitialized is false in both calls
            logger = LogManager.GetLogger("LogName");

            logger.InfoFormat("[PID:{0}] [THID:{1}] BEGIN Static constructor",
               Process.GetCurrentProcess().Id,
               Thread.CurrentThread.ManagedThreadId);
        }
        catch (Exception exception)
        {
           logger.Error("error on type construction stage", exception);
        }
        finally
        {
            logger.InfoFormat("[PID:{0}] [THID:{1}] END Static constructor",
               Process.GetCurrentProcess().Id,
               Thread.CurrentThread.ManagedThreadId);               
           typeInitialized = true;
        }
    }
}
like image 530
sll Avatar asked Dec 25 '12 14:12

sll


1 Answers

Assuming you're hosting your service with IIS, this is normal behaviour unless you explicitly configure the process to only permit a single AppDomain from being spun up.

If you look at the list of running processes, you'll find each process Id in your log corresponds with a copy of w3wp.exe hosting a separate appdomain.

like image 185
Bevan Avatar answered Oct 14 '22 08:10

Bevan