views:

42

answers:

1

Hi.

I have a question regarding use of interfaces when unmanaged resources come to play. Suppose I have a web service and generated WCF client. Service contract looks like this:

[ServiceContract]
public interface ITestService
{
    [OperationContract]
    string GetData(int value);
}

On client side I use dependency injection and bind ITestService interface to TestServiceClient (generated with svcutil). However, when I create ITestService and it really is TestServiceClient it should be disposed in correct way but the clients don't know about it. How do you deal with this problem?

I thought about generating proxy classes like this:

class TestServiceClientProxy : ITestService
{
    #region ITestService Members

    public string GetData(int value)
    {
        var client = new TestServiceClient();
        bool success = false;
        try
        {
            var result = client.GetData(value);
            client.Close();
            success = true;
            return result;
        }
        finally
        {
            if (!success)
            {
                client.Abort();
            }
        }
    }

    #endregion
}

However, I don't think code generation would be best way to go. Should I use some AOP framework or DynamicProxy?

Thanks in advance for help.

A: 

Declare that your interface implements IDisposable, implement Dispose() in the concrete class, and your DI provider will dispose it properly. If your DI provider doesn't do this, find a new one.

[ServiceContract]
public interface ITestService : IDisposable
{
    [OperationContract]
    string GetData(int value);
}
Jamie Ide
@Josh Einstein: This is not about services but about clients
empi
@Jame Ide: Adding IDisposable to my interface definition forces users of my service to remember to release it through DI container. What is more, if I want to create service mock I would need to define Dispose that is completely unnecessary.
empi
@empi, My mistake you are correct. I interpreted the question to be how to "dipose" the server side of the service via a client's implementation of IDisposable.
Josh Einstein