private object Invoke(Type type, string[] methodNames, IServiceCollection services)
        {
            if (type == null)
            {
                return(null);
            }

            MethodInfo method = null;

            // ReSharper disable once ForCanBeConvertedToForeach
            for (var i = 0; i < methodNames.Length; i++)
            {
                method = type.GetTypeInfo().GetDeclaredMethod(methodNames[i]);
                if (method != null)
                {
                    break;
                }
            }

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

            try
            {
                var instance = !method.IsStatic
                    ? ActivatorUtilities.GetServiceOrCreateInstance(GetHostServices(), type)
                    : null;

                var parameters = method.GetParameters();
                var arguments  = new object[parameters.Length];
                for (var i = 0; i < parameters.Length; i++)
                {
                    var parameterType = parameters[i].ParameterType;
                    arguments[i] = parameterType == typeof(IServiceCollection)
                        ? services
                        : ActivatorUtilities.GetServiceOrCreateInstance(GetHostServices(), parameterType);
                }

                return(method.Invoke(instance, arguments));
            }
            catch (Exception ex)
            {
                if (ex is TargetInvocationException)
                {
                    ex = ex.InnerException;
                }

                _logger.Value.LogWarning(
                    DesignCoreStrings.InvokeStartupMethodFailed(method.Name, type.DisplayName(), ex.Message));
                _logger.Value.LogDebug(ex.ToString());

                return(null);
            }
        }
Beispiel #2
0
        public void Invoke_warns_on_error()
        {
            var log = new List <Tuple <LogLevel, string> >();

            var startup = new StartupInvoker(
                new LazyRef <ILogger>(() => new ListLoggerFactory(log).CreateLogger("Test")),
                MockAssembly.Create(typeof(BadStartup)),
                /*environment:*/ null,
                "Irrelevant");

            var services = startup.ConfigureServices();

            Assert.NotNull(services);
            Assert.Equal(
                DesignCoreStrings.InvokeStartupMethodFailed(
                    "ConfigureServices",
                    nameof(BadStartup),
                    "Something went wrong."),
                log[0].Item2);
        }