I have a WCF service and I have the following (simplified) class:

public class PerOperationSingleton : IDisposable
{
    private static bool _hasInstance = false;

    public PerOperationSingleton()
    {
        if(_hasInstance)
            throw new InvalidOperationException("Cannot have multiple instances during a single WCF operation");

        _hasInstance = true;
    }

    public void Dispose()
    {
        _hasInstance = false;
    }
}

I guess, it's pretty self explanatory piece of code. I don't need a singleton for entire WCF service but only during a single operation call. If one instance of the PerOperationSingleton is disposed, it should be safe to create a new instance during the same WCF operation.

The problem is that I don't know how to make the _hasInstance variable to be effective only for one WCF operation. I know about [ThreadStatic], but I've heard that ASP.NET and WCF do not guarantee that an operation will be executed on a single thread - it might be transferred to another thread.

I definitely don't want my _hasInstance = true to move to thread pool and get incorrectly detected if some other operation picks that thread from the pool.

If WCF operation moves to another thread, I would like the _hasInstance variable to keep the "true" value if it was set.

And I don't want to change some global settings for my WCF service to avoid affecting the performance or get into some problems which will be hard to debug and solve later (I don't feel proficient enough in advanced ASP.NET and WCF topics).

I cannot store _hasInstance in session either because my client requested to disable .NET sessions for various reasons.

I would like the class PerOperationSingleton actually to be environment agnostic. It shouldn't really know anything about WCF or ASP.NET.

How do I make _hasInstance variable static during entire call of my WCF operation and don't affect other WCF operations?

有帮助吗?

解决方案

I would consider using OperationContext to make you data "static" during the operation call.

Here is a similar discussion Where to store data for current WCF call? Is ThreadStatic safe?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top