【问题标题】:C# IDisposable object for entire class整个类的 C# IDisposable 对象
【发布时间】:2011-04-20 19:41:13
【问题描述】:

我目前正在处理的项目在类的每个方法中都使用 IDisposable 对象。在每个方法的开头重新键入 using 块已经开始变得乏味,并且想知道是否有一种方法可以指定一个一次性变量以用于类的每个方法?

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...
        }
    }
}

【问题讨论】:

    标签: c# refactoring code-reuse using-statement


    【解决方案1】:

    不,没有什么特别针对此的。你可以写:

    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);
        }
    }
    

    我不确定它是否会特别有益。

    (请注意,我必须将其从原始版本中的 Action&lt;TestDataContext&gt; 更改为 Func&lt;TestDataContext, T&gt;,因为您希望能够从您的方法中返回值。)

    【讨论】:

    • 我从您的回复中学到了一些东西 - 一直在尝试了解 lambda 表达式并在现实世界中使用它们。谢谢。
    • 不错的解决方案...唯一的问题是如何使单元测试更容易...我使用 IOC 注入上下文工厂,所以我想我回答了我自己的问题...
    【解决方案2】:

    坦率地说,我会保留冗长的代码,但使用 sn-p 而不是每次都输入它。 使用special tool 创建您自己的sn-p 或使用Texter 等文本替换工具

    【讨论】:

      【解决方案3】:

      也许一个简单的重构是你能做的最好的事情,而不用诉诸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>();
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-16
        • 2010-10-10
        • 1970-01-01
        • 2010-09-20
        • 2011-01-27
        • 2010-11-12
        • 2011-06-11
        • 1970-01-01
        相关资源
        最近更新 更多