stopa
stopa

Reputation: 1

Ambient context scope WCF instance provider

I'm intend to use the ambient context scope in my project, which is described at this location. I's a client/server application, the clients are connected by WCF services. The question is now how to implement an WCF instance provider. The approach that I tried always gets an error message "System.InvalidOperationException: DbContextScope instances must be disposed of in the order in which they were created!" when the context should be disposed.

Has anybody a solution to manage that?

Code snipped of my instance provider:

public class MyInstanceProvider<T> : IInstanceProvider, IContractBehavior where T : class
{
    DbContextScopeFactory _dbContextScopeFactory;
    Dictionary<int, IDbContextScope> _Contexts = new Dictionary<int, IDbContextScope>();

    public MyInstanceProvider( DbContextScopeFactory dbContextScopeFactory )
    {
        _dbContextScopeFactory = dbContextScopeFactory;
    }

    public object GetInstance( InstanceContext instanceContext )
    {
        IDbContextScope contextScope = _dbContextScopeFactory.Create();
        _Contexts[instanceContext.GetHashCode()] = contextScope;
        var _Repository = new RepositoryFactory<T>().GetInstance();

        return _Repository;
    }

    public object GetInstance( InstanceContext instanceContext, Message message )
    {
        return GetInstance( instanceContext );
    }

    public void ReleaseInstance( InstanceContext instanceContext, object instance )
    {
        var hashCode = instanceContext.GetHashCode();
        if (_Contexts.ContainsKey( hashCode ))
        {
            var contextScope = _Contexts[hashCode];
            contextScope.Dispose();
            _Contexts.Clear();
        }
    }

...

Upvotes: 0

Views: 246

Answers (1)

Igor Labutin
Igor Labutin

Reputation: 1446

There are three potential issues in your code.

  1. It is not good to use instanceContext.GetHashCode() as dictionary key - hash codes are not guaranteed to be unique. Just use instanceContext itself.

  2. In the ReleaseInstance method you check if dictionary has proper key, dispose the contextScope and then clean the whole dictionary (_Contexts.Clear()). I think you should replace _Contexts.Clear() with _Contexts.Remove.

  3. You use usual Dictionary while your code may be executed in multiple threads by WCF. Better use ConcurrentDictionary.

Upvotes: 1

Related Questions