【问题标题】:How to ensure using the using keyword on a resource如何确保在资源上使用 using 关键字
【发布时间】:2016-02-07 13:01:08
【问题描述】:

是否有可能确保 VS 项目中使用特定方法(返回 Nhibernate 会话)的每个开发人员都将强制使用 using 模式。 例如:

      public static ISession GetSession()
        {
            ISessionFactory holder = ActiveRecordMediator.GetSessionFactoryHolder();
            ISessionScope activeScope = holder.ThreadScopeInfo.GetRegisteredScope();
            ISession session = null;
            var key = holder.GetSessionFactory(typeof(ActiveRecordBase));
            if (activeScope == null)
            {
                session = holder.CreateSession(typeof(ActiveRecordBase));
            }           
            return session;
        }
我想确保每个调用这个方法的开发者都用 using 语句包围它,否则它会被 Visual Studio 视为错误并且不会编译。 (或者也许通过一些分析托管代码的工具)。 只能按以下方式使用:
using (var session = Nh.GetSession())
{
    //use the session   
}

【问题讨论】:

    标签: c# memory-management nhibernate dispose idisposable


    【解决方案1】:

    是否有可能确保 VS 项目中的每个开发人员 使用某种方法(返回 Nhibernate 会话)将是 强制使用模式?

    简单的答案是否定的。

    更广泛的问题是,如果用户在超出范围之前没有 Dispose 任何 Disposable 对象,是否可以警告用户。 CodeRush 和 FxCop 在这方面提供了某种警告。

    即使使用最新的 resharper 版本,我也没有看到这样的警告。 Herehere 是关于 resharper 的一些讨论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      • 2010-12-18
      • 2015-09-18
      • 1970-01-01
      • 2011-08-12
      相关资源
      最近更新 更多