C # IDisposable object for whole class

The project I'm currently working on uses an IDisposable object for each method in the class. He began to get the tedious re-entry of the use block at the beginning of each method and wondered if there was a way to specify a one-time variable to use in each 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...
        }
    }
}
+3
source share
3 answers

No, this is nothing special. You can 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 am not sure if this would be particularly helpful.

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

+13

, , , . , Texter

+3

Perhaps simple refactoring is the best you can do without resorting to something like PostSharp :

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

Source: https://habr.com/ru/post/1767875/


All Articles