Nat*_*222 31 .net c# garbage-collection idisposable ninject
所以,我有一个从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;
}
Run Code Online (Sandbox Code Playgroud)
我有一个全局DataUnitOfWork对象(实现IDisposable),当服务调用进来时,Ninject通过构造函数参数实例化.当调试时,如果我使用
using(_unitOfWork)
Run Code Online (Sandbox Code Playgroud)
超出范围后,_unitOfWork对象立即被释放,然后被Ninject再次调用(尽管它被标记为已丢弃,因此没有任何反应.)如果没有using语句,Ninject将处理处理.
长话短说,这是否有一般的经验法则?在我阅读的所有内容似乎表明永远不会使用它,或者在某些折衷的情况下使用它之后,我一直害怕整个IDisposable的东西,但它总是让我感到困惑.
任何输入都表示赞赏.
哦,当我在这里打字时,为什么在处理时确实有GC.SuppressFinalize()的调用?Dispose和Finalize有何不同?
Rem*_*oor 49
CLR文档指出,创建Disposable对象的任何人都负责调用Dispose.在这种情况下,对象由Ninject创建.这意味着你应该不显式调用处置.
Ninject处理具有另一个范围的每个Disposable对象,而不是InTransientScope 只要GC收集与创建的对象绑定的范围对象.这就是为什么每个Disposable对象应该是Bindd的范围不是InTransientScope().例如,你可以使用InParentScope()从该NamedScope扩展将尽快处置对象为对象时,它被注入到被垃圾收集.