Edit: The best solution is to always return an IDisposable object, even if the object doesn't need to be disposed. That way, the framework user doesn't have to keep checking for IDisposable all the time.
Your framework would look like this:
public interface IFoo : IDisposable
{
void Invoke();
}
public class DataAccessBase : IFoo
{
public void Invoke()
{
Console.WriteLine("In Invoke() in DataAccessBase.");
}
public void Dispose()
{
Console.WriteLine("In Dispose() in DataAccessBase.");
}
}
public static class DataAccessFactory
{
public static IFoo Resolve()
{
return new DataAccessBase();
}
}
And it is consumed as you'd expect:
private static void TestPolymorphismWithDisposable()
{
using(IFoo foo = DataAccessFactory.Resolve())
{
foo.Invoke();
}
}
However, If you're a user and you're stuck with a result which may or may not implement IDisposable, you would need to consume it as follows:
private static void TestPolymorphismWithDisposable()
{
IFoo foo = DataAccessFactory.Resolve();
using(foo as IDisposable)
{
foo.Invoke(); //This is always executed regardless of whether IDisposable is implemented
//Dispose is called if IDisposable was implemented
}
}
See these questions: Using statement with a null object and Using 'as IDisposable' in a using block