Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

c# - Guidelines For Dispose() and Ninject

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

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)

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.

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.

Any input is appreciated.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...