本文介绍了Dispose() 和 Ninject 指南的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个从 WCF 服务公开的方法:

So, I have a method exposed from a WCF service as such:

public GetAllCommentsResponse GetAllComments(GetAllCommentsRequest request)
{
    var response = new GetAllCommentsResponse();

    using(_unitOfWork)
        try
        {
            Guard.ArgNotNull(request, "request");

            var results = _unitOfWork.CommentRepository.Get(d => d.Id > 0).ToArray();

            //... Do rest of stuff here
        }
        catch (Exception ex)
        {
            response.Success = false;
            response.FailureInformation = ex.Message;
            Logger.LogError("GetAllComments Method Failed", ex);
        }

    return response;
}

我有一个全局 DataUnitOfWork 对象(它实现了 IDisposable),当服务调用进入时,它由 Ninject 通过构造函数参数实例化.调试时,如果我使用

I have a global DataUnitOfWork object (which implements IDisposable) that gets instantiated by Ninject through a constructor argument when a service call comes in. When debugging, if I use

using(_unitOfWork)

_unitOfWork 对象在超出范围后立即被释放,然后被 Ninject 再次调用(尽管它被标记为已释放,所以什么都没有发生.)如果没有 using 语句,Ninject 会处理释放.

the _unitOfWork object gets disposed immediately after going out of scope then gets called again by Ninject (although it's been marked as disposed, so nothing happens.) Without the using statement, Ninject handles the disposing.

长话短说,这有一般的经验法则吗?在我读到的所有内容似乎都表明永远不要使用它或在某些不拘一格的情况下使用它之后,我一直害怕整个 IDisposable 东西,但它总是让我感到困惑.

Long story short, is there a general rule of thumb for this? I've been scared of the whole IDisposable thing after everything I read seems to indicate never to use it, or use it in certain eclectic situations, but it's always confused me.

感谢任何输入.

哦,虽然我在这里打字,但为什么在处理时会调用 GC.SuppressFinalize()?Dispose 和 Finalize 有何不同?

Oh, also while I'm here typing anyway, why exactly is there a call to GC.SuppressFinalize() when disposing? How do Dispose and Finalize differ?

推荐答案

CLR 文档指出,创建 Disposable 对象的人负责调用 Dispose.在这种情况下,对象是由 Ninject 创建的.这意味着您应该显式调用 Dispose.

The CLR documentation states that whoever creates a Disposable object is responsible for calling Dispose. In this case the object is created by Ninject. That means you should not call Dispose explicitly.

Ninject 会处理除 InTransientScope 一旦创建对象所绑定的范围对象被 GC 收集.这就是为什么每个 Disposable 对象都应该使用不是 InTransientScope() 的范围进行 Bindd.例如.您可以使用 NamedScope 扩展 中的 InParentScope() 来处理对象一旦注入的对象被垃圾回收.

Ninject disposes every Disposable object that has another scope other than InTransientScope as soon as the scope object to which the created object is tied is collected by GC. That's why every Disposable object should be Bindd with a scope that is not InTransientScope(). E.g. you can use InParentScope() from the NamedScope extension which will Dispose the object as soon as the object it is injected into is garbage collected.

这篇关于Dispose() 和 Ninject 指南的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-16 16:21