51 lines
1.4 KiB
C#
51 lines
1.4 KiB
C#
using System;
|
|
|
|
namespace FlowScope.Container
|
|
{
|
|
internal sealed class ContainerRegistration
|
|
{
|
|
private readonly Container _owner;
|
|
private readonly Func<Container, object> _factory;
|
|
private readonly bool _ownsCreatedInstance;
|
|
private object _instance;
|
|
private bool _created;
|
|
|
|
private ContainerRegistration(Container owner, Func<Container, object> factory, object instance, bool created, bool ownsCreatedInstance)
|
|
{
|
|
_owner = owner;
|
|
_factory = factory;
|
|
_instance = instance;
|
|
_created = created;
|
|
_ownsCreatedInstance = ownsCreatedInstance;
|
|
}
|
|
|
|
public static ContainerRegistration ForInstance(object instance)
|
|
{
|
|
return new ContainerRegistration(null, null, instance, true, false);
|
|
}
|
|
|
|
public static ContainerRegistration ForFactory(Container owner, Func<Container, object> factory)
|
|
{
|
|
return new ContainerRegistration(owner, factory, null, false, true);
|
|
}
|
|
|
|
public object Resolve()
|
|
{
|
|
if (_created)
|
|
{
|
|
return _instance;
|
|
}
|
|
|
|
_instance = _factory(_owner);
|
|
_created = true;
|
|
|
|
if (_ownsCreatedInstance && _instance is IDisposable disposable)
|
|
{
|
|
_owner.TrackOwnedDisposable(disposable);
|
|
}
|
|
|
|
return _instance;
|
|
}
|
|
}
|
|
}
|