Skip to content

Commit

Permalink
Fix singletons created during dispose
Browse files Browse the repository at this point in the history
* because we accessed the instance to check if it is disposable and created the instance during this, so now we have a method on the TypeInformation that can access the singletonInstance directly without lazy creating it
  • Loading branch information
susch19 committed Nov 13, 2024
1 parent e525efa commit e78f250
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
13 changes: 7 additions & 6 deletions NonSucking.Framework.Extension/IoC/StandaloneTypeContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,12 @@ public override T GetUnregistered<T>() where T : class
public override void Dispose()
{
typeRegister.Clear();
typeInformationRegister.Values
.Where(t => t.Behaviour == InstanceBehaviour.Singleton && t.Instance != this)
.Select(t => t.Instance as IDisposable)
.ToList()
.ForEach(i => i?.Dispose());

typeInformationRegister.Remove(typeof(StandaloneTypeContainer));
typeInformationRegister.Remove(typeof(ITypeContainer));

foreach (var item in typeInformationRegister.Values)
item.TryDispose();

typeInformationRegister.Clear();
typeInformationSemaphore.Dispose();
Expand All @@ -144,7 +145,7 @@ internal override void BuildCtorInformation(CtorInformation info)

public override void Remove<T>()
=> Remove(typeof(T));


public override void Remove(Type type)
=> typeInformationRegister.Remove(type);
Expand Down
13 changes: 13 additions & 0 deletions NonSucking.Framework.Extension/IoC/TypeInformation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,19 @@ public void RecreateUncompleteCtors()

Completed = !ctors.Any(c => !c.IsComplete);
}

/// <summary>
/// Disposed the singleton instance, if existing and required
/// </summary>
public void TryDispose()
{
if (Behaviour != InstanceBehaviour.Singleton
|| singeltonInstance is not null)
return;
if (singeltonInstance is IDisposable disposable)
disposable.Dispose();

}
}

}

0 comments on commit e78f250

Please sign in to comment.