Search code examples
c#refactoringcode-reuseusing-statement

C# IDisposable object for entire class


The project that I'm working on at the moment uses an IDisposable object in every method in a class. It has started getting tedious re-typing the using block at the start of every method, and was wondering if there was a way to specify a disposable variable for use in every method of the class?

public static class ResourceItemRepository
{
    public static ResourceItem GetById(int id)
    {
        using (var db = DataContextFactory.Create<TestDataContext>())
        {
            // Code goes here...
        }
    }
    public static List<ResourceItem> GetInCateogry(int catId)
    {
        using (var db = DataContextFactory.Create<TestDataContext>())
        {
            // Code goes here...
        }
    }
    public static ResourceItem.Type GetType(int id)
    {
        using (var db = DataContextFactory.Create<TestDataContext>())
        {
            // Code goes here...
        }
    }
}

Solution

  • No, there's nothing particularly geared towards this. You could write:

    public static ResourceItem GetById(int id)
    {
        WithDataContext(db =>
        {
            // Code goes here...
        });
    }
    
    // Other methods here, all using WithDataContext
    
    // Now the only method with a using statement:
    private static T WithDataContext<T>(Func<TestDataContext, T> function)
    {
        using (var db = DataContextFactory.Create<TestDataContext>())
        {
            return function(db);
        }
    }
    

    I'm not sure that it would be particularly beneficial though.

    (Note that I've had to change it from Action<TestDataContext> in my original version to Func<TestDataContext, T> as you want to be able to return values from your methods.)