/// <summary> /// 获取可释放对象列表 /// </summary> /// <param name="serviceScope">范围容器</param> /// <returns>可释放对象列表</returns> private static IList <IDisposable> GetDisposableInstances(IServiceScope serviceScope) { #region # 验证 if (serviceScope == null) { return(new List <IDisposable>()); } #endregion IList <IDisposable> disposables = new List <IDisposable>(); Type serviceScopeType = serviceScope.GetType(); #if NET45 const string scopeProviderFieldName = "_scopedProvider"; const string transientDisposablesFieldName = "_transientDisposables"; FieldInfo scopeProviderField = serviceScopeType.GetField(scopeProviderFieldName, BindingFlags.NonPublic | BindingFlags.Instance); object scopeProvider = scopeProviderField?.GetValue(serviceScope); Type scopeProviderType = scopeProvider?.GetType(); FieldInfo transientDisposablesField = scopeProviderType?.GetField(transientDisposablesFieldName, BindingFlags.NonPublic | BindingFlags.Instance); if (transientDisposablesField?.GetValue(scopeProvider) is List <IDisposable> list) { disposables = list; } #else const string disposablesFieldName = "_disposables"; FieldInfo disposablesField = serviceScopeType.GetField(disposablesFieldName, BindingFlags.NonPublic | BindingFlags.Instance); if (disposablesField?.GetValue(serviceScope) is List <object> list) { disposables = list.Select(x => (IDisposable)x).ToList(); } #endif return(disposables); }
/// <summary> /// 范围容器是否已被释放 /// </summary> /// <param name="serviceScope">范围容器</param> /// <returns>是否已被释放</returns> public static bool Disposed(this IServiceScope serviceScope) { #region # 验证 if (serviceScope == null) { return(true); } #endregion bool disposed; Type type = serviceScope.GetType(); #if NET45 const string scopedProviderFieldName = "_scopedProvider"; const string disposeCalledFieldName = "_disposeCalled"; FieldInfo scopedProviderField = type.GetField(scopedProviderFieldName, BindingFlags.NonPublic | BindingFlags.Instance); object scopedProvider = scopedProviderField.GetValue(serviceScope); Type scopedProviderType = scopedProviderField.FieldType; FieldInfo disposeCalledField = scopedProviderType.GetField(disposeCalledFieldName, BindingFlags.NonPublic | BindingFlags.Instance); object value = disposeCalledField.GetValue(scopedProvider); disposed = (bool)value; #else const string disposedFieldName = "_disposed"; FieldInfo disposedField = type.GetField(disposedFieldName, BindingFlags.NonPublic | BindingFlags.Instance); object value = disposedField.GetValue(serviceScope); disposed = (bool)value; #endif return(disposed); }