/// <summary> /// Create target info for request /// </summary> /// <returns></returns> public ImmutableLinkedList <InjectionTargetInfo> CreateTargetInfo() { if (_targetInfoList != null) { return(_targetInfoList); } var targetName = ""; if (Info is ParameterInfo info) { targetName = info.Name; } else if (Info is MemberInfo memberInfo) { targetName = memberInfo.Name; } var targetInfo = new InjectionTargetInfo(Services.AttributeDiscoveryService, InjectedType, RequestingStrategy, Info, targetName, RequestType, ActivationType, false, null, UniqueId); _targetInfoList = Parent?.CreateTargetInfo() ?? ImmutableLinkedList <InjectionTargetInfo> .Empty; _targetInfoList = _targetInfoList.Add(targetInfo); return(_targetInfoList); }
/// <summary> /// Create target info for request /// </summary> /// <param name="targetInfos">child targets</param> /// <returns></returns> public ImmutableLinkedList <InjectionTargetInfo> CreateTargetInfo(ImmutableLinkedList <InjectionTargetInfo> targetInfos) { targetInfos = Parent?.CreateTargetInfo(targetInfos) ?? targetInfos; if (_targetInfo != null) { return(targetInfos.Add(_targetInfo)); } var targetName = ""; if (Info is ParameterInfo) { targetName = ((ParameterInfo)Info).Name; } else if (Info is MemberInfo) { targetName = ((MemberInfo)Info).Name; } _targetInfo = new InjectionTargetInfo(Services.AttributeDiscoveryService, InjectedType, RequestingStrategy, Info, targetName, RequestType, ActivationType, false, null, UniqueId); return(targetInfos.Add(_targetInfo)); }
private static void CreateMessageForTargetInfo(StringBuilder builder, InjectionTargetInfo info, int stepIndex) { builder.AppendFormat("{0} Importing {1} ", stepIndex, info.LocateType); var parameter = info.InjectionTarget as ParameterInfo; if (parameter != null) { var method = parameter.Member as MethodInfo; if (method != null) { builder.AppendFormat(" for method {0} parameter {1}", method.Name, parameter.Name); } else { builder.AppendFormat(" for constructor parameter {0}", parameter.Name); } } else if (info.InjectionTarget is PropertyInfo) { builder.AppendFormat(" for property {0}", ((PropertyInfo)info.InjectionTarget).Name); } builder.AppendLine(); }
public void Verify(InjectionConsumerInfo consumer) { Requires.IsNotNull(consumer, nameof(consumer)); InjectionTargetInfo target = consumer.Target; if (target.TargetType.IsValueType() || target.TargetType == typeof(string)) { throw new ActivationException(StringResources.TypeMustNotContainInvalidInjectionTarget(target)); } }
/// <summary> /// Check if a dependency can be resolved (i less dependencies) /// </summary> /// <param name="target">Details about the parameter</param> /// <param name="injectedInto">Details about the type the parameter is to be injected into</param> /// <returns>True if the exception canl be resolved</returns> public bool CanResolve(InjectionTargetInfo target, Type injectedInto) { // if the type of the parameter is handled... var resolvable = AllowedTypes.Contains(target.TargetType); if (resolvable) { // ... then try a matching entry in the application configuration file VerifyAppSettings(target.Name, injectedInto.Name); } return(resolvable); }
public bool CanResolve(InjectionTargetInfo target) { bool resolvable = target.TargetType == typeof(string) && target.Name.EndsWith(ConnectionStringPostFix) && target.Name.LastIndexOf(ConnectionStringPostFix) > 0; if (resolvable) { this.VerifyConfigurationFile(target); } return(resolvable); }
public bool CanResolve(InjectionTargetInfo target) { bool resolvable = target.TargetType == typeof(string) && target.Name.EndsWith(ConnectionStringPostFix) && target.Name.LastIndexOf(ConnectionStringPostFix) > 0; if (resolvable) { this.VerifyConfigurationFile(target); } return resolvable; }
private static string GetConnectionString(InjectionTargetInfo target) { string name = target.Name.Substring(0, target.Name.LastIndexOf(ConnectionStringPostFix)); var settings = ConfigurationManager.ConnectionStrings[name]; if (settings == null) { throw new ActivationException( "No connection string with name '" + name + "' could be found in the " + "application's configuration file."); } return(settings.ConnectionString); }
private string GetConnectionString(InjectionTargetInfo target) { string name = target.Name.Substring(0, target.Name.LastIndexOf(ConnectionStringPostFix)); var connectionString = this.connectionStringRetriever(name); if (connectionString == null) { throw new ActivationException( "No connection string with name '" + name + "' could be found in the " + "application's configuration file."); } return(connectionString); }
private ThreadLocal <object> FindThreadLocal(InjectionTargetInfo target) { Dictionary <Type, ThreadLocal <object> > parameterLocals; if (this.implementationLocals.TryGetValue(target.Member.DeclaringType, out parameterLocals)) { ThreadLocal <object> local; if (parameterLocals.TryGetValue(target.TargetType, out local)) { return(local); } } return(null); }
public bool CanResolve(InjectionTargetInfo target) { Type type = target.TargetType; bool resolvable = (type.IsValueType || type == typeof(string)) && target.Name.EndsWith(AppSettingsPostFix) && target.Name.LastIndexOf(AppSettingsPostFix) > 0; if (resolvable) { this.VerifyConfigurationFile(target); } return(resolvable); }
private InstanceProducer GetInstanceProducerFor(InjectionConsumerInfo consumer) { InjectionTargetInfo target = consumer.Target; InstanceProducer producer = this.container.GetRegistrationEvenIfInvalid(target.TargetType, consumer); if (producer == null) { // By redirecting to Verify() we let the verify throw an expressive exception. If it doesn't // we throw the exception ourselves. this.container.Options.DependencyInjectionBehavior.Verify(consumer); this.container.ThrowParameterTypeMustBeRegistered(target); } return(producer); }
private InstanceProducer ApplyDecorator(InjectionTargetInfo target, Expression expression, List <PredicatePair> predicatePairs) { var visitor = new ContextualDecoratorExpressionVisitor(target, predicatePairs); expression = visitor.Visit(expression); if (!visitor.AllContextualDecoratorsApplied) { throw new InvalidOperationException("Couldn't apply the contextual decorator " + visitor.UnappliedDecorators.Last().ToFriendlyName() + ". Make sure that all " + "registered decorators that wrap this decorator are transient and don't depend on " + "Func<" + target.TargetType.ToFriendlyName() + ">."); } return(InstanceProducer.FromExpression(target.TargetType, expression, this.container)); }
private static object GetAppSettingValue(InjectionTargetInfo target) { string key = target.Name.Substring(0, target.Name.LastIndexOf(AppSettingsPostFix)); string configurationValue = ConfigurationManager.AppSettings[key]; if (configurationValue != null) { TypeConverter converter = TypeDescriptor.GetConverter(target.TargetType); return(converter.ConvertFromString(null, CultureInfo.InvariantCulture, configurationValue)); } throw new ActivationException( "No application setting with key '" + key + "' could be found in the " + "application's configuration file."); }
public InstanceProducer?GetInstanceProducer(InjectionConsumerInfo consumer, bool throwOnFailure) { Requires.IsNotNull(consumer, nameof(consumer)); InjectionTargetInfo target = consumer.Target; InstanceProducer?producer = this.container.GetRegistrationEvenIfInvalid(target.TargetType, consumer); if (producer == null && throwOnFailure) { // By redirecting to Verify() we let the verify throw an expressive exception. If it doesn't // we throw the exception ourselves. this.container.Options.DependencyInjectionBehavior.Verify(consumer); this.container.ThrowParameterTypeMustBeRegistered(target); } return(producer); }
bool IParameterConvention.CanResolve(InjectionTargetInfo target) { return(target.Parameter != null && this.GetParameter(target.Parameter) != null); }
/// <inheritdoc /> public override bool CanResolve(InjectionTargetInfo target) => target.TargetType == typeof(string) && target.Name == "logName";
public bool CanResolve(InjectionTargetInfo target) { bool resolvable = target.Name == Consts.ModelParameterName; if (resolvable) { _modelType = target.TargetType; } return resolvable; }
public bool CanResolve(InjectionTargetInfo target) { return target.Parameter != null && target.GetCustomAttributes(typeof(OptionalAttribute), true).Length > 0; }
internal static string ParameterTypeMustBeRegistered(InjectionTargetInfo target, int count) { if (target.Parameter != null) { return string.Format(CultureInfo.InvariantCulture, "The constructor of type {0} contains the parameter with name '{1}' and type {2} that " + "is not registered. Please ensure {2} is registered, or change the constructor of {0}.{3}", target.Member.DeclaringType.ToFriendlyName(), target.Name, target.TargetType.ToFriendlyName(), GetAdditionalInformationAboutExistingConditionalRegistrations(target, count)); } else { return string.Format(CultureInfo.InvariantCulture, "Type {0} contains the property with name '{1}' and type {2} that is not registered. " + "Please ensure {2} is registered, or change {0}.{3}", target.Member.DeclaringType.ToFriendlyName(), target.Name, target.TargetType.ToFriendlyName(), GetAdditionalInformationAboutExistingConditionalRegistrations(target, count)); } }
private void VerifyConfigurationFile(InjectionTargetInfo target) { GetConnectionString(target); }
public ContextualDecoratorExpressionVisitor(InjectionTargetInfo target, List<PredicatePair> predicatePairs) { this.target = target; this.predicatePairs = predicatePairs; }
public bool CanResolve(InjectionTargetInfo target) => target.Parameter != null && target.GetCustomAttributes(typeof(OptionalAttribute), true).Any();
public bool CanResolve(InjectionTargetInfo target) { return(target.Parameter != null && target.GetCustomAttributes(typeof(OptionalAttribute), true).Length > 0); }
/// <inheritdoc /> public abstract bool CanResolve(InjectionTargetInfo target);
/// <inheritdoc /> public override bool CanResolve(InjectionTargetInfo target) => target.TargetType == typeof(DateTime) && target.Name == "getUtcNow";
private void VerifyConfigurationFile(InjectionTargetInfo target) { GetAppSettingValue(target); }
internal static string TypeMustNotContainInvalidInjectionTarget(InjectionTargetInfo invalidTarget) { string reason = string.Empty; if (invalidTarget.TargetType.Info().IsValueType) { reason = " because it is a value type"; } if (invalidTarget.Parameter != null) { return string.Format(CultureInfo.InvariantCulture, "The constructor of type {0} contains parameter '{1}' of type {2} which can not be used " + "for constructor injection{3}.", invalidTarget.Member.DeclaringType.ToFriendlyName(), invalidTarget.Name, invalidTarget.TargetType.ToFriendlyName(), reason); } else { return string.Format(CultureInfo.InvariantCulture, "The type {0} contains property '{1}' of type {2} which can not be used for property " + "injection{3}.", invalidTarget.Member.DeclaringType.ToFriendlyName(), invalidTarget.Name, invalidTarget.TargetType.ToFriendlyName(), reason); } }
private static object GetAppSettingValue(InjectionTargetInfo target) { string key = target.Name.Substring(0, target.Name.LastIndexOf(AppSettingsPostFix)); string configurationValue = ConfigurationManager.AppSettings[key]; if (configurationValue != null) { TypeConverter converter = TypeDescriptor.GetConverter(target.TargetType); return converter.ConvertFromString(null, CultureInfo.InvariantCulture, configurationValue); } throw new ActivationException( "No application setting with key '" + key + "' could be found in the " + "application's configuration file."); }
private static string GetConnectionString(InjectionTargetInfo target) { string name = target.Name.Substring(0, target.Name.LastIndexOf(ConnectionStringPostFix)); var settings = ConfigurationManager.ConnectionStrings[name]; if (settings == null) { throw new ActivationException( "No connection string with name '" + name + "' could be found in the " + "application's configuration file."); } return settings.ConnectionString; }
public Expression GetConstructorExpression(out ConstructorInfo constructorInfo, out IEnumerable<Expression> constructorParameters) { CompiledExportDelegateInfo exportDelegateInfo = _instanceCompiledExport.exportDelegateInfo; constructorInfo = _instanceCompiledExport.exportDelegateInfo.ImportConstructor ?? _instanceCompiledExport.PickConstructor(exportDelegateInfo.ActivationType); if (constructorInfo == null) { throw new PublicConstructorNotFoundException(exportDelegateInfo.ActivationType); } List<Expression> parameters = new List<Expression>(); constructorParameters = parameters; Attribute[] constructorAttributes = constructorInfo.GetCustomAttributes(true).ToArray(); if (constructorAttributes.Length == 0) { constructorAttributes = EmptyAttributesArray; } foreach (ParameterInfo parameterInfo in constructorInfo.GetParameters()) { Attribute[] parameterAttributes = parameterInfo.GetCustomAttributes(true).ToArray(); if (parameterAttributes.Length == 0) { parameterAttributes = EmptyAttributesArray; } IExportValueProvider valueProvider = null; ExportStrategyFilter exportStrategyFilter = null; string importName = null; object comparerObject = null; ILocateKeyValueProvider locateKey = null; if (exportDelegateInfo.ConstructorParams != null) { foreach (ConstructorParamInfo constructorParamInfo in exportDelegateInfo.ConstructorParams) { if (string.Compare(parameterInfo.Name, constructorParamInfo.ParameterName, StringComparison.OrdinalIgnoreCase) == 0) { importName = constructorParamInfo.ImportName; exportStrategyFilter = constructorParamInfo.ExportStrategyFilter; valueProvider = constructorParamInfo.ValueProvider; comparerObject = constructorParamInfo.ComparerObject; locateKey = constructorParamInfo.LocateKeyProvider; break; } } if (valueProvider == null) { foreach (ConstructorParamInfo constructorParamInfo in exportDelegateInfo.ConstructorParams) { if (string.IsNullOrEmpty(constructorParamInfo.ParameterName) && parameterInfo.ParameterType.GetTypeInfo().IsAssignableFrom( constructorParamInfo.ParameterType.GetTypeInfo())) { importName = constructorParamInfo.ImportName; exportStrategyFilter = constructorParamInfo.ExportStrategyFilter; valueProvider = constructorParamInfo.ValueProvider; comparerObject = constructorParamInfo.ComparerObject; locateKey = constructorParamInfo.LocateKeyProvider; break; } } } } InjectionTargetInfo targetInfo = null; if (importName != null) { targetInfo = new InjectionTargetInfo(exportDelegateInfo.ActivationType, _instanceCompiledExport.activationTypeAttributes, parameterInfo, parameterAttributes, constructorAttributes, importName, null); } else if (InjectionKernel.ImportTypeByName(parameterInfo.ParameterType)) { targetInfo = new InjectionTargetInfo(exportDelegateInfo.ActivationType, _instanceCompiledExport.activationTypeAttributes, parameterInfo, parameterAttributes, constructorAttributes, parameterInfo.Name, null); } else { targetInfo = new InjectionTargetInfo(exportDelegateInfo.ActivationType, _instanceCompiledExport.activationTypeAttributes, parameterInfo, parameterAttributes, constructorAttributes, null, parameterInfo.ParameterType); } ParameterExpression parameterExpression = _instanceCompiledExport.CreateImportExpression(parameterInfo.ParameterType, targetInfo, ExportStrategyDependencyType.ConstructorParameter, importName, parameterInfo.Name + "CVar", true, valueProvider, exportStrategyFilter, locateKey, comparerObject, null); parameters.Add(Expression.Convert(parameterExpression, parameterInfo.ParameterType)); } Expression constructExpression = Expression.New(constructorInfo, parameters.ToArray()); return Expression.Assign(_instanceCompiledExport.instanceVariable, constructExpression); }
public ContextualDecoratorExpressionVisitor(InjectionTargetInfo target, List <PredicatePair> predicatePairs) { this.target = target; this.predicatePairs = predicatePairs; }
internal static string ParameterTypeMustBeRegistered(InjectionTargetInfo target, int numberOfConditionals, bool hasRelatedOneToOneMapping, bool hasRelatedCollectionMapping, Type[] skippedDecorators) => target.Parameter != null ? string.Format(CultureInfo.InvariantCulture, "The constructor of type {0} contains the parameter with name '{1}' and type {2} that " + "is not registered. Please ensure {2} is registered, or change the constructor of {0}.{3}{4}{5}{6}", target.Member.DeclaringType.ToFriendlyName(), target.Name, target.TargetType.ToFriendlyName(), GetAdditionalInformationAboutExistingConditionalRegistrations(target, numberOfConditionals), DidYouMeanToDependOnNonCollectionInstead(hasRelatedOneToOneMapping, target.TargetType), DidYouMeanToDependOnCollectionInstead(hasRelatedCollectionMapping, target.TargetType), NoteThatSkippedDecoratorsWereFound(target.TargetType, skippedDecorators)) : string.Format(CultureInfo.InvariantCulture, "Type {0} contains the property with name '{1}' and type {2} that is not registered. " + "Please ensure {2} is registered, or change {0}.{3}{4}{5}{6}", target.Member.DeclaringType.ToFriendlyName(), target.Name, target.TargetType.ToFriendlyName(), GetAdditionalInformationAboutExistingConditionalRegistrations(target, numberOfConditionals), DidYouMeanToDependOnNonCollectionInstead(hasRelatedOneToOneMapping, target.TargetType), DidYouMeanToDependOnCollectionInstead(hasRelatedCollectionMapping, target.TargetType), NoteThatSkippedDecoratorsWereFound(target.TargetType, skippedDecorators));
private void VerifyConfigurationFile(InjectionTargetInfo target) { this.GetAppSettingValue(target); }
private static string GetAdditionalInformationAboutExistingConditionalRegistrations( InjectionTargetInfo target, int numberOfConditionalRegistrations) { string serviceTypeName = target.TargetType.ToFriendlyName(); bool isGenericType = target.TargetType.Info().IsGenericType; string openServiceTypeName = isGenericType ? target.TargetType.GetGenericTypeDefinition().ToFriendlyName() : target.TargetType.ToFriendlyName(); if (numberOfConditionalRegistrations > 1) { return string.Format(CultureInfo.InvariantCulture, " {0} conditional registrations for {1} exist{2}, but none of the supplied predicates " + "returned true when provided with the contextual information for {3}.", numberOfConditionalRegistrations, openServiceTypeName, isGenericType ? (" that are applicable to " + serviceTypeName) : string.Empty, target.Member.DeclaringType.ToFriendlyName()); } else if (numberOfConditionalRegistrations == 1) { return string.Format(CultureInfo.InvariantCulture, " 1 conditional registration for {0} exists{1}, but its supplied predicate didn't " + "return true when provided with the contextual information for {2}.", openServiceTypeName, isGenericType ? (" that is applicable to " + serviceTypeName) : string.Empty, target.Member.DeclaringType.ToFriendlyName()); } else { return string.Empty; } }
public bool CanResolve(InjectionTargetInfo target) { Type type = target.TargetType; bool resolvable = (type.IsValueType || type == typeof(string)) && target.Name.EndsWith(AppSettingsPostFix) && target.Name.LastIndexOf(AppSettingsPostFix) > 0; if (resolvable) { this.VerifyConfigurationFile(target); } return resolvable; }