private object GetInstance(Type type, bool throwError) { var scope = IoCScope.GetCurrent(); var hasScope = scope != null; if (hasScope && scope.TryGetInstance(type, out object instance)) { return(instance); } var hasRegistration = _registrator.TryGet(type, out IIoCRegistration registration); if (hasRegistration && registration.MustBeScoped && !hasScope) { if (throwError) { throw new InvalidOperationException($"The type {type.FullName} could not be created since it requires a scope"); } else { return(null); } } var newInstance = _factory.GetInstance(type, throwError); if (newInstance == null) { return(null); } if (hasScope) { if (hasRegistration) { if (!registration.CanBeScoped) { return(newInstance); } scope.Register(registration, newInstance); } else { scope.Register(newInstance); } } return(newInstance); }
public void Dispose() { if (_instances != null) { foreach (var instance in _instances.Values) { if (instance.Registration != null) { instance.Registration.Unload(instance.Instance); } else { (instance.Instance as IDisposable)?.Dispose(); } } _instances = null; } var storedScope = ScopeLocal.Value; IoCScope childScope = null; while (storedScope != null && !ReferenceEquals(storedScope, this)) { childScope = storedScope; storedScope = storedScope.Parent; } if (storedScope == null) { throw new ArgumentException("The scope could not be found in the scope chain"); } if (childScope != null) { childScope.Parent = storedScope.Parent; } else { ScopeLocal.Value = storedScope.Parent; } }