Пример #1
0
        internal Expression ApplyLifetime(ExpressionBuilder expressionBuilder, ServiceRegistration serviceRegistration,
                                          ResolutionContext resolutionContext, Type requestedType)
        {
            if (resolutionContext.CurrentContainerContext.ContainerConfiguration.LifetimeValidationEnabled &&
                this.LifeSpan > 0)
            {
                if (resolutionContext.CurrentLifeSpan > this.LifeSpan)
                {
                    throw new LifetimeValidationFailedException(serviceRegistration.ImplementationType,
                                                                $"The life-span of {serviceRegistration.ImplementationType} ({this.Name}|{this.LifeSpan}) " +
                                                                $"is shorter than its direct or indirect parent's {resolutionContext.NameOfServiceLifeSpanValidatingAgainst}." + Environment.NewLine +
                                                                "This could lead to incidental lifetime promotions with longer life-span, it's recommended to double check your lifetime configurations.");
                }

                resolutionContext = resolutionContext.BeginLifetimeValidationContext(this.LifeSpan,
                                                                                     $"{serviceRegistration.ImplementationType} ({this.Name}|{this.LifeSpan})");
            }

            if (!this.StoreResultInLocalVariable)
            {
                return(this.BuildLifetimeAppliedExpression(expressionBuilder,
                                                           serviceRegistration, resolutionContext, requestedType));
            }

            var variable = resolutionContext.GetKnownVariableOrDefault(serviceRegistration.RegistrationId);

            if (variable != null)
            {
                return(variable);
            }

            var resultExpression = this.BuildLifetimeAppliedExpression(expressionBuilder,
                                                                       serviceRegistration, resolutionContext, requestedType);

            if (resultExpression == null)
            {
                return(null);
            }

            variable = requestedType.AsVariable();
            resolutionContext.AddDefinedVariable(serviceRegistration.RegistrationId, variable);
            resolutionContext.AddInstruction(variable.AssignTo(resultExpression));
            return(variable);
        }