views:

34

answers:

1

I have an interface (IDbAccess) for a database access class so that I can unit test it using Unity. It all works fine in Unity and now I want to make the concrete database class implement IDisposable so that it closes the db connections.

My problem is that Unity does not understand that my concrete class is disposable because the interface (IDbAccess) cannot implement another interface.

So how can I write code like this (pseudo code) so that Unity is aware that it needs to dispose the class as soon as I am done?

Using var MyDbAccessInstance = Unity.Resolve<IDbAccess>
{
}

Thanks

Ryan

+1  A: 

You could in theory create a new interface IMyDbAccess which inherits both IDisposable and IDbAccess. So something like

public interface IMyDbAccess : IDbAccess, IDisposable
{
}

public class MyClass : IMyDbAccess
{
    // Stuff from IDbAccess

    public void Dispose()
    {
    }
}

Would let you:

IUnityContainer unityContainer = new UnityContainer();

using (var bob = unityContainer.Resolve<IMyDbAccess>())
{
    // something
}

Don't forget to change your lifetime manager to ExternallyControlledLifetimeManager when you register the type so that the container has a weak reference to the class.

John Mc