Пример #1
0
        public void CreateHostBuilderPattern__Invalid_CantFindServiceProvider()
        {
            var factory = HostFactoryResolver.ResolveServiceProviderFactory(typeof(CreateHostBuilderInvalidSignature.Program).Assembly, s_WaitTimeout);

            Assert.NotNull(factory);
            Assert.Throws <InvalidOperationException>(() => factory(Array.Empty <string>()));
        }
Пример #2
0
        public void NoSpecialEntryPointPatternHangs()
        {
            var factory = HostFactoryResolver.ResolveServiceProviderFactory(typeof(NoSpecialEntryPointPatternHangs.Program).Assembly, s_WaitTimeout);

            Assert.NotNull(factory);
            Assert.Throws <InvalidOperationException>(() => factory(Array.Empty <string>()));
        }
Пример #3
0
        public void CreateWebHostBuilderPattern__InvalidReturnType_CanFindServiceProvider()
        {
            var factory = HostFactoryResolver.ResolveServiceProviderFactory(typeof(CreateWebHostBuilderInvalidSignature.Program).Assembly);

            Assert.NotNull(factory);
            Assert.Null(factory(Array.Empty <string>()));
        }
Пример #4
0
        public void BuildWebHostPattern_CanFindWebHost()
        {
            var factory = HostFactoryResolver.ResolveWebHostFactory <IWebHost>(typeof(BuildWebHostPatternTestSite.Program).Assembly);

            Assert.NotNull(factory);
            Assert.IsAssignableFrom <IWebHost>(factory(Array.Empty <string>()));
        }
Пример #5
0
        public void CreateWebHostBuilderPattern_CanFindServiceProvider()
        {
            var factory = HostFactoryResolver.ResolveServiceProviderFactory(typeof(CreateWebHostBuilderPatternTestSite.Program).Assembly);

            Assert.NotNull(factory);
            Assert.IsAssignableFrom <IServiceProvider>(factory(Array.Empty <string>()));
        }
Пример #6
0
        public void NoSpecialEntryPointPatternMainNoArgs()
        {
            var factory = HostFactoryResolver.ResolveServiceProviderFactory(typeof(NoSpecialEntryPointPatternMainNoArgs.Program).Assembly, s_WaitTimeout);

            Assert.NotNull(factory);
            Assert.IsAssignableFrom <IServiceProvider>(factory(Array.Empty <string>()));
        }
Пример #7
0
        public void CreateHostBuilderPattern_CanFindHostBuilder()
        {
            var factory = HostFactoryResolver.ResolveHostBuilderFactory <MockHostTypes.IHostBuilder>(typeof(CreateHostBuilderPatternTestSite.Program).Assembly);

            Assert.NotNull(factory);
            Assert.IsAssignableFrom <MockHostTypes.IHostBuilder>(factory(Array.Empty <string>()));
        }
Пример #8
0
        public void TopLevelStatements()
        {
            var assembly = Assembly.Load("TopLevelStatements");
            var factory  = HostFactoryResolver.ResolveServiceProviderFactory(assembly, s_WaitTimeout);

            Assert.NotNull(factory);
            Assert.IsAssignableFrom <IServiceProvider>(factory(Array.Empty <string>()));
        }
Пример #9
0
        public void TopLevelStatementsTestsTimeout()
        {
            var assembly = Assembly.Load("TopLevelStatementsTestsTimeout");
            var factory  = HostFactoryResolver.ResolveServiceProviderFactory(assembly, s_WaitTimeout);

            Assert.NotNull(factory);
            Assert.Throws <InvalidOperationException>(() => factory(Array.Empty <string>()));
        }
    private IServiceProvider?CreateFromHosting(string[] args)
    {
        _reporter.WriteVerbose(DesignStrings.FindingHostingServices);

        var serviceProviderFactory = HostFactoryResolver.ResolveServiceProviderFactory(_startupAssembly);

        if (serviceProviderFactory == null)
        {
            _reporter.WriteVerbose(DesignStrings.NoCreateHostBuilder);

            return(null);
        }

        var aspnetCoreEnvironment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
        var dotnetEnvironment     = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
        var environment           = aspnetCoreEnvironment
                                    ?? dotnetEnvironment
                                    ?? "Development";

        if (aspnetCoreEnvironment == null)
        {
            Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", environment);
        }

        if (dotnetEnvironment == null)
        {
            Environment.SetEnvironmentVariable("DOTNET_ENVIRONMENT", environment);
        }

        _reporter.WriteVerbose(DesignStrings.UsingEnvironment(environment));

        try
        {
            var services = serviceProviderFactory(args);
            if (services == null)
            {
                _reporter.WriteWarning(DesignStrings.MalformedCreateHostBuilder);

                return(null);
            }

            _reporter.WriteVerbose(DesignStrings.UsingHostingServices);

            return(services.CreateScope().ServiceProvider);
        }
        catch (Exception ex)
        {
            if (ex is TargetInvocationException)
            {
                ex = ex.InnerException !;
            }

            _reporter.WriteVerbose(ex.ToString());
            _reporter.WriteWarning(DesignStrings.InvokeCreateHostBuilderFailed(ex.Message));

            return(null);
        }
    }
Пример #11
0
        public void ApplicationNameSetFromArgument()
        {
            Assembly         assembly        = Assembly.Load("ApplicationNameSetFromArgument");
            var              factory         = HostFactoryResolver.ResolveServiceProviderFactory(assembly, s_WaitTimeout);
            IServiceProvider?serviceProvider = factory(Array.Empty <string>());

            var configuration = (IConfiguration)serviceProvider.GetService(typeof(IConfiguration));

            Assert.Contains("ApplicationNameSetFromArgument", configuration["applicationName"]);
        }
Пример #12
0
        /// <summary>
        /// Creates a <see cref="IHostBuilder"/> used to set up <see cref="TestServer"/>.
        /// </summary>
        /// <remarks>
        /// The default implementation of this method looks for a <c>public static IHostBuilder CreateHostBuilder(string[] args)</c>
        /// method defined on the entry point of the assembly of <typeparamref name="TEntryPoint" /> and invokes it passing an empty string
        /// array as arguments.
        /// </remarks>
        /// <returns>A <see cref="IHostBuilder"/> instance.</returns>
        protected virtual IHostBuilder CreateHostBuilder()
        {
            var hostBuilder = HostFactoryResolver.ResolveHostBuilderFactory <IHostBuilder>(typeof(TEntryPoint).Assembly)?.Invoke(Array.Empty <string>());

            if (hostBuilder != null)
            {
                hostBuilder.UseEnvironment(Environments.Development);
            }
            return(hostBuilder);
        }
Пример #13
0
        public void NoSpecialEntryPointPatternThrows()
        {
            using var _ = RemoteExecutor.Invoke(() =>
            {
                var factory = HostFactoryResolver.ResolveServiceProviderFactory(typeof(NoSpecialEntryPointPatternThrows.Program).Assembly, s_WaitTimeout);

                Assert.NotNull(factory);
                Assert.Throws <Exception>(() => factory(Array.Empty <string>()));
            });
        }
Пример #14
0
        public void NoSpecialEntryPointPattern()
        {
            using var _ = RemoteExecutor.Invoke(() =>
            {
                var factory = HostFactoryResolver.ResolveServiceProviderFactory(typeof(NoSpecialEntryPointPattern.Program).Assembly, s_WaitTimeout);

                Assert.NotNull(factory);
                Assert.IsAssignableFrom <IServiceProvider>(factory(Array.Empty <string>()));
            });
        }
Пример #15
0
    public int Process()
    {
        var assemblyName   = new AssemblyName(_context.AssemblyName);
        var assembly       = Assembly.Load(assemblyName);
        var entryPointType = assembly.EntryPoint?.DeclaringType;

        if (entryPointType == null)
        {
            _reporter.WriteError(Resources.FormatMissingEntryPoint(_context.AssemblyPath));
            return(3);
        }

        try
        {
            var serviceFactory = HostFactoryResolver.ResolveServiceProviderFactory(assembly);
            if (serviceFactory == null)
            {
                _reporter.WriteError(Resources.FormatMethodsNotFound(
                                         HostFactoryResolver.BuildWebHost,
                                         HostFactoryResolver.CreateHostBuilder,
                                         HostFactoryResolver.CreateWebHostBuilder,
                                         entryPointType));

                return(4);
            }

            var services = serviceFactory(Array.Empty <string>());
            if (services == null)
            {
                _reporter.WriteError(Resources.FormatServiceProviderNotFound(
                                         typeof(IServiceProvider),
                                         HostFactoryResolver.BuildWebHost,
                                         HostFactoryResolver.CreateHostBuilder,
                                         HostFactoryResolver.CreateWebHostBuilder,
                                         entryPointType));

                return(5);
            }

            var success = GetDocuments(services);
            if (!success)
            {
                return(6);
            }
        }
        catch (Exception ex)
        {
            _reporter.WriteError(ex.ToString());
            return(7);
        }

        return(0);
    }
        private IServiceProvider CreateFromHosting(string[] args)
        {
            _reporter.WriteVerbose(DesignStrings.FindingHostingServices);

            var serviceProviderFactory = HostFactoryResolver.ResolveServiceProviderFactory(_startupAssembly);
            if (serviceProviderFactory == null)
            {
                _reporter.WriteVerbose(DesignStrings.NoCreateHostBuilder);

                return null;
            }

            // TODO: Remove when dotnet/cli#6617 is fixed
            var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            if (environment == null)
            {
                environment = "Development";
                Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", environment);
            }

            _reporter.WriteVerbose(DesignStrings.UsingEnvironment(environment));

            try
            {
                var services = serviceProviderFactory(args);
                if (services == null)
                {
                    _reporter.WriteWarning(DesignStrings.MalformedCreateHostBuilder);

                    return null;
                }

                _reporter.WriteVerbose(DesignStrings.UsingHostingServices);

                return services.CreateScope().ServiceProvider;
            }
            catch (Exception ex)
            {
                if (ex is TargetInvocationException)
                {
                    ex = ex.InnerException;
                }

                _reporter.WriteVerbose(ex.ToString());
                _reporter.WriteWarning(DesignStrings.InvokeCreateHostBuilderFailed(ex.Message));

                return null;
            }
        }
Пример #17
0
        public void NoSpecialEntryPointPatternHostBuilderConfigureHostBuilderCallbackIsCalled()
        {
            bool called = false;

            void ConfigureHostBuilder(object hostBuilder)
            {
                Assert.IsAssignableFrom <IHostBuilder>(hostBuilder);
                called = true;
            }

            var factory = HostFactoryResolver.ResolveHostFactory(typeof(NoSpecialEntryPointPattern.Program).Assembly, waitTimeout: s_WaitTimeout, configureHostBuilder: ConfigureHostBuilder);

            Assert.NotNull(factory);
            Assert.IsAssignableFrom <IHost>(factory(Array.Empty <string>()));
            Assert.True(called);
        }
Пример #18
0
        public void NoSpecialEntryPointPatternBuildsThenThrowsCallsEntryPointCompletedCallbackWithException()
        {
            var       wait = new ManualResetEventSlim(false);
            Exception?entryPointException = null;

            void EntryPointCompleted(Exception?exception)
            {
                entryPointException = exception;
                wait.Set();
            }

            var factory = HostFactoryResolver.ResolveHostFactory(typeof(NoSpecialEntryPointPatternBuildsThenThrows.Program).Assembly, waitTimeout: s_WaitTimeout, stopApplication: false, entrypointCompleted: EntryPointCompleted);

            Assert.NotNull(factory);
            Assert.IsAssignableFrom <IHost>(factory(Array.Empty <string>()));
            Assert.True(wait.Wait(s_WaitTimeout));
            Assert.NotNull(entryPointException);
        }
Пример #19
0
        public void NoSpecialEntryPointPatternCanRunInParallel()
        {
            var factory = HostFactoryResolver.ResolveServiceProviderFactory(typeof(NoSpecialEntryPointPattern.Program).Assembly, s_WaitTimeout);

            Assert.NotNull(factory);

            var tasks = new Task <IServiceProvider> [30];
            int index = 0;

            for (int i = 0; i < tasks.Length; i++)
            {
                tasks[index++] = Task.Run(() => factory(Array.Empty <string>()));
            }

            Task.WaitAll(tasks);

            foreach (var t in tasks)
            {
                Assert.IsAssignableFrom <IServiceProvider>(t.Result);
            }
        }
Пример #20
0
        public void CreateWebHostBuilderPattern__Invalid_CantFindWebHostBuilder()
        {
            var factory = HostFactoryResolver.ResolveWebHostBuilderFactory <IWebHostBuilder>(typeof(CreateWebHostBuilderInvalidSignature.Program).Assembly);

            Assert.Null(factory);
        }
Пример #21
0
        public void BuildWebHostPattern__Invalid_CantFindServiceProvider()
        {
            var factory = HostFactoryResolver.ResolveServiceProviderFactory(typeof(BuildWebHostInvalidSignature.Program).Assembly);

            Assert.NotNull(factory);
        }
Пример #22
0
        public void BuildWebHostPattern__Invalid_CantFindWebHost()
        {
            var factory = HostFactoryResolver.ResolveWebHostFactory <IWebHost>(typeof(BuildWebHostInvalidSignature.Program).Assembly);

            Assert.Null(factory);
        }
Пример #23
0
        public void CreateHostBuilderPattern__Invalid_CantFindServiceProvider()
        {
            var factory = HostFactoryResolver.ResolveServiceProviderFactory(typeof(CreateHostBuilderInvalidSignature.Program).Assembly);

            Assert.Null(factory);
        }
Пример #24
0
        internal static IServiceProvider GetServiceProviderWithHostFactoryResolver(Assembly assembly)
        {
#if NETCOREAPP2_1 || NETFRAMEWORK
            return(null);
#else
            // We're disabling the default server and the console host lifetime. This will disable:
            // 1. Listening on ports
            // 2. Logging to the console from the default host.
            // This is essentially what the test server does in order to get access to the application's
            // IServicerProvider *and* middleware pipeline.
            void ConfigureHostBuilder(object hostBuilder)
            {
                ((IHostBuilder)hostBuilder).ConfigureServices((context, services) =>
                {
                    services.AddSingleton <IServer, NoopServer>();
                    services.AddSingleton <IHostLifetime, NoopHostLifetime>();
                });
            }

            var waitForStartTcs = new TaskCompletionSource <object>();

            void OnEntryPointExit(Exception exception)
            {
                // If the entry point exited, we'll try to complete the wait
                if (exception != null)
                {
                    waitForStartTcs.TrySetException(exception);
                }
                else
                {
                    waitForStartTcs.TrySetResult(null);
                }
            }

            // If all of the existing techniques fail, then try to resolve the ResolveHostFactory
            var factory = HostFactoryResolver.ResolveHostFactory(assembly,
                                                                 stopApplication: false,
                                                                 configureHostBuilder: ConfigureHostBuilder,
                                                                 entrypointCompleted: OnEntryPointExit);

            // We're unable to resolve the factory. This could mean the application wasn't referencing the right
            // version of hosting.
            if (factory == null)
            {
                return(null);
            }

            try
            {
                // Get the IServiceProvider from the host
#if NET6_0_OR_GREATER
                var assemblyName = assembly.GetName()?.FullName ?? string.Empty;
                // We should set the application name to the startup assembly to avoid falling back to the entry assembly.
                var services = ((IHost)factory(new[] { $"--{HostDefaults.ApplicationKey}={assemblyName}" })).Services;
#else
                var services = ((IHost)factory(Array.Empty <string>())).Services;
#endif

                // Wait for the application to start so that we know it's fully configured. This is important because
                // we need the middleware pipeline to be configured before we access the ISwaggerProvider in
                // in the IServiceProvider
                var applicationLifetime = services.GetRequiredService <IHostApplicationLifetime>();

                using (var registration = applicationLifetime.ApplicationStarted.Register(() => waitForStartTcs.TrySetResult(null)))
                {
                    waitForStartTcs.Task.Wait();
                    return(services);
                }
            }
            catch (InvalidOperationException)
            {
                // We're unable to resolve the host, swallow the exception and return null
            }

            return(null);
#endif
        }
        public static IWebHostBuilder CreateFromAssemblyEntryPoint(Assembly assembly, string[] args)
        {
            var factory = HostFactoryResolver.ResolveWebHostBuilderFactory <IWebHostBuilder>(assembly);

            return(factory?.Invoke(args));
        }