MVC3:CA2000 - 有什么方法可以解决内核未处理警告不足的问题吗?

发布于 2024-12-15 18:47:58 字数 510 浏览 3 评论 0原文

在使用 Ninject 的 MVC3 项目上运行代码分析时,我收到以下警告:

警告 1 CA2000:Microsoft.Reliability:方法中 “NinjectMVC3.CreateKernel()”,对象“kernel”未一起处理 所有异常路径。对对象调用 System.IDisposable.Dispose 'kernel' 在所有对它的引用超出范围之前。

我知道我可以轻松地抑制该消息,但我很好奇是否有更好的方法来解决该警告。静态方法显然意味着返回“内核”,因此不应丢弃它。

    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        RegisterServices(kernel);
        return kernel;
    }

不是一个大问题,只是一个学习练习。

When running code analysis on my MVC3 project that uses Ninject, I receive the following warning:

Warning 1 CA2000 : Microsoft.Reliability : In method
'NinjectMVC3.CreateKernel()', object 'kernel' is not disposed along
all exception paths. Call System.IDisposable.Dispose on object
'kernel' before all references to it are out of scope.

I understand I can easily suppress the message but am curious if there is a better way to resolve the warning. The static method is obviously meant to return 'kernel' so one should not dispose of it.

    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        RegisterServices(kernel);
        return kernel;
    }

Not a major problem, just a learning exercise.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瑾夏年华 2024-12-22 18:47:58

CA2000 在这里检测到的问题是,如果在实例化对象和从方法返回之间抛出异常,则实例化对象将被“孤立”而无需处置。在大多数情况下,我倾向于认为这种情况下的解决方法比问题更糟糕。但是,如果您想修复它并且无法使用 Darin 建议的方法,那么这里有一个应该通过 CA2000 验证的替代版本:

private static IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    try
    {
        RegisterServices(kernel);
        return kernel;
    }
    catch
    {
        kernel.Dispose();
        throw;
    }
}

The problem that CA2000 is detecting here is that the instantiated object will be "orphaned" without disposition if an exception is thrown between its instantiation and its return from the method. In most cases, I would tend to consider the cure to be worse than the problem for such scenarios. However, if you wish to fix it and use of the approach suggested by Darin is not an option, here's an alternate version that should pass CA2000 verification:

private static IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    try
    {
        RegisterServices(kernel);
        return kernel;
    }
    catch
    {
        kernel.Dispose();
        throw;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文