gpt4 book ai didi

c# - Dispose() 和 Ninject 指南

转载 作者:IT王子 更新时间:2023-10-29 04:09:29 25 4
gpt4 key购买 nike

因此,我有一个从 WCF 服务公开的方法:

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 通过构造函数参数实例化。调试时,如果我使用

using(_unitOfWork)

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

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

欢迎任何意见。

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

最佳答案

CLR 文档指出,无论谁创建 Disposable 对象,都有责任调用 Dispose。在这种情况下,对象由 Ninject 创建。这意味着您不应该显式调用 Dispose。

Ninject 处置具有除 InTransientScope 之外的另一个范围的每个 Disposable 对象 as soon as the scope object to which the created object is tied is collected by GC .这就是为什么每个 Disposable 对象都应该 Bindd 的范围不是 InTransientScope()。例如。您可以使用 the NamedScope extension 中的 InParentScope()一旦被注入(inject)的对象被垃圾回收,它将立即处置该对象。

关于c# - Dispose() 和 Ninject 指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10234802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com