コード例 #1
0
ファイル: IoCContainer.cs プロジェクト: jaygumji/Enigma
        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);
        }