private Func <IServiceProvider, object> CreateBuilder(IServiceProvider services) { var servicesArgument = Expression.Parameter(typeof(IServiceProvider), "services"); var constructorParameters = _constructor.GetParameters(); var parameters = new Expression[constructorParameters.Length]; for (var i = constructorParameters.Length - 1; i >= 0; i--) { var parameter = constructorParameters[i]; var parameterType = parameter.ParameterType; var required = !parameter.HasDefaultValue; var parameterDependency = required ? _dependencyEngine.GetRequiredDependency(parameterType) : _dependencyEngine.GetDependency(parameterType); parameters[i] = parameterDependency == null ? Expression.Default(parameterType) : BuildParameter(parameterDependency, parameterType, services, servicesArgument); } var body = Expression.New(_constructor, parameters); return(Expression.Lambda <Func <IServiceProvider, object> >(body, servicesArgument).Compile()); }
public static DependencyLifetime DefineLifetime(this IDependencyEngine engine, Type implementation) { var constructor = ReflectionUtils.GetConstructor(implementation); if (constructor == null) { throw Error.DefaultConstructorNotFound(implementation); } var parameters = constructor.GetParameters(); var dependencies = new LocalList <DependencyLifetime>(); foreach (var parameter in parameters) { var required = !parameter.HasDefaultValue; var dependency = required ? engine.GetRequiredDependency(parameter.ParameterType) : engine.GetDependency(parameter.ParameterType); if (dependency != null) { dependencies.Add(dependency.Lifetime); } } return(dependencies.DefineLifetime()); }
protected void EnsureValidDependenciesLifetime( ConstructorInfo constructor, DependencyLifetime dependedLifetime, IDependencyEngine engine) { var parameters = constructor.GetParameters(); foreach (var parameter in parameters) { var dependencyType = parameter.ParameterType; var dependency = parameter.IsOptional ? engine.GetDependency(dependencyType) : engine.GetRequiredDependency(dependencyType); if (dependency == null) { continue; } var dependencyLifetime = dependency.Lifetime; if (dependedLifetime == DependencyLifetime.Singleton && dependencyLifetime == DependencyLifetime.Scoped) { throw Error.InconsistentLifetime(Implementation, dependedLifetime, dependencyType, dependencyLifetime); } } }