예제 #1
0
        public void StartupWithTwoConfigureServicesThrows()
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance <IFakeStartupCallback>(this);
            var services = serviceCollection.BuildServiceProvider();

            var diagnosticMessages = new List <string>();
            var hostingEnv         = new HostingEnvironment {
                EnvironmentName = "TwoConfigureServices"
            };
            var loader = new StartupLoader(services, hostingEnv);
            var type   = loader.FindStartupType("Microsoft.AspNet.Hosting.Tests", diagnosticMessages);

            var ex = Assert.Throws <InvalidOperationException>(() => loader.LoadMethods(type, diagnosticMessages));

            Assert.Equal("Having multiple overloads of method 'ConfigureServices' is not supported.", ex.Message);
        }
예제 #2
0
        public void StartupWithPrivateConfiguresThrows()
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance <IFakeStartupCallback>(this);
            var services = serviceCollection.BuildServiceProvider();

            var diagnosticMessages = new List <string>();
            var hostingEnv         = new HostingEnvironment {
                EnvironmentName = "PrivateConfigure"
            };
            var loader = new StartupLoader(services, hostingEnv);
            var type   = loader.FindStartupType("Microsoft.AspNet.Hosting.Tests", diagnosticMessages);

            var ex = Assert.Throws <InvalidOperationException>(() => loader.LoadMethods(type, diagnosticMessages));

            Assert.Equal("A public method named 'ConfigurePrivateConfigure' or 'Configure' could not be found in the 'Microsoft.AspNet.Hosting.Fakes.StartupPrivateConfigure' type.", ex.Message);
        }
예제 #3
0
        public void StartupClassAddsConfigureServicesToApplicationServices(string environment)
        {
            var services = new ServiceCollection().BuildServiceProvider();

            var type    = StartupLoader.FindStartupType("Microsoft.AspNetCore.Hosting.Tests", environment);
            var startup = StartupLoader.LoadMethods(services, type, environment);

            var app = new ApplicationBuilder(services);

            app.ApplicationServices = startup.ConfigureServicesDelegate(new ServiceCollection());
            startup.ConfigureDelegate(app);

            var options = app.ApplicationServices.GetRequiredService <IOptions <FakeOptions> >().Value;

            Assert.NotNull(options);
            Assert.True(options.Configured);
            Assert.Equal(environment, options.Environment);
        }
예제 #4
0
        public void StartupClassWithConfigureServicesShouldMakeServiceAvailableInConfigure()
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton <IServiceProviderFactory <IServiceCollection>, DefaultServiceProviderFactory>();
            var services = serviceCollection.BuildServiceProvider();

            var type    = StartupLoader.FindStartupType("Microsoft.AspNetCore.Hosting.Tests", "WithConfigureServices");
            var startup = StartupLoader.LoadMethods(services, type, "WithConfigureServices");

            var app = new ApplicationBuilder(services);

            app.ApplicationServices = startup.ConfigureServicesDelegate(serviceCollection);
            startup.ConfigureDelegate(app);

            var foo = app.ApplicationServices.GetRequiredService <StartupWithConfigureServices.IFoo>();

            Assert.True(foo.Invoked);
        }
예제 #5
0
        public void StartupClassAddsConfigureServicesToApplicationServicesCaseInsensitive(string environment)
        {
            var services = new ServiceCollection()
                           .AddSingleton <IServiceProviderFactory <IServiceCollection>, DefaultServiceProviderFactory>()
                           .BuildServiceProvider();
            var type    = StartupLoader.FindStartupType("Microsoft.AspNetCore.Hosting.Tests", environment);
            var startup = StartupLoader.LoadMethods(services, type, environment);

            var app = new ApplicationBuilder(services);

            app.ApplicationServices = startup.ConfigureServicesDelegate(new ServiceCollection());
            startup.ConfigureDelegate(app); // By this not throwing, it found "ConfigureCaseInsensitive"

            var options = app.ApplicationServices.GetRequiredService <IOptions <FakeOptions> >().Value;

            Assert.NotNull(options);
            Assert.True(options.Configured);
            Assert.Equal("ConfigureCaseInsensitiveServices", options.Environment);
        }
예제 #6
0
        public void StartupClassMayHaveHostingServicesInjected()
        {
            var callbackStartup   = new FakeStartupCallback();
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton <IServiceProviderFactory <IServiceCollection>, DefaultServiceProviderFactory>();
            serviceCollection.AddSingleton <IFakeStartupCallback>(callbackStartup);
            var services = serviceCollection.BuildServiceProvider();

            var type    = StartupLoader.FindStartupType("Microsoft.AspNetCore.Hosting.Tests", "WithServices");
            var startup = StartupLoader.LoadMethods(services, type, "WithServices");

            var app = new ApplicationBuilder(services);

            app.ApplicationServices = startup.ConfigureServicesDelegate(serviceCollection);
            startup.ConfigureDelegate(app);

            Assert.Equal(2, callbackStartup.MethodsCalled);
        }
        private void RegisterComponent(IServiceCollection services, IMvcBuilder builder,
                                       Assembly assembly,
                                       List <HisarCacheAttribute> cacheItems)
        {
            var assemblyName = assembly.GetName().Name;
            var componentId  = assembly.GetComponentId();

            ComponentAssemblyLookup.Add(componentId, assembly);

            AssemblyLoadContext.Default.Resolving += DefaultResolving;

            if (cacheItems != null)
            {
                cacheItems.AddRange(assembly.GetTypesAttributes <HisarCacheAttribute>());
            }

            try
            {
                var startupType = StartupLoader.FindStartupType(assemblyName, _env.EnvironmentName);
                if (startupType != null)
                {
                    var startup = StartupTypeLoader.CreateHisarConventionBasedStartup(startupType, ServiceProvider, _env);
                    StartupLookup.Add(componentId, startup);
                    startup.ConfigureServices(services);

                    services.AddMenuBuilders(startupType);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                AssemblyLoadContext.Default.Resolving -= null;
            }

            var components  = assembly.GetTypes().ToArray();
            var controllers = components.Where(c => IsController(c.GetTypeInfo())).ToList();

            builder.PartManager.ApplicationParts.Add(new TypesPart(components));
        }
예제 #8
0
        public void StartupClassCanHandleConfigureServicesThatReturnsNull()
        {
            var serviceCollection = new ServiceCollection();
            var services          = serviceCollection.BuildServiceProvider();

            var diagnosticMessages = new List <string>();
            var hostingEnv         = new HostingEnvironment {
                EnvironmentName = "WithNullConfigureServices"
            };
            var loader  = new StartupLoader(services, hostingEnv);
            var type    = loader.FindStartupType("Microsoft.AspNet.Hosting.Tests", diagnosticMessages);
            var startup = loader.LoadMethods(type, diagnosticMessages);

            var app = new ApplicationBuilder(services);

            app.ApplicationServices = startup.ConfigureServicesDelegate(new ServiceCollection());
            Assert.NotNull(app.ApplicationServices);
            startup.ConfigureDelegate(app);
            Assert.NotNull(app.ApplicationServices);
        }
예제 #9
0
        public void StartupClassMayHaveHostingServicesInjected()
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance <IFakeStartupCallback>(this);
            var services = serviceCollection.BuildServiceProvider();

            var diagnosticMessages = new List <string>();
            var hostingEnv         = new HostingEnvironment {
                EnvironmentName = "WithServices"
            };
            var loader  = new StartupLoader(services, hostingEnv);
            var type    = loader.FindStartupType("Microsoft.AspNet.Hosting.Tests", diagnosticMessages);
            var startup = loader.LoadMethods(type, diagnosticMessages);

            var app = new ApplicationBuilder(services);

            app.ApplicationServices = startup.ConfigureServicesDelegate(serviceCollection);
            startup.ConfigureDelegate(app);

            Assert.Equal(2, _configurationMethodCalledList.Count);
        }
예제 #10
0
        public void StartupClassWithConfigureServicesShouldMakeServiceAvailableInConfigure()
        {
            var serviceCollection = new ServiceCollection();
            var services          = serviceCollection.BuildServiceProvider();

            var diagnosticMessages = new List <string>();
            var hostingEnv         = new HostingEnvironment {
                EnvironmentName = "WithConfigureServices"
            };
            var loader  = new StartupLoader(services, hostingEnv);
            var type    = loader.FindStartupType("Microsoft.AspNet.Hosting.Tests", diagnosticMessages);
            var startup = loader.LoadMethods(type, diagnosticMessages);

            var app = new ApplicationBuilder(services);

            app.ApplicationServices = startup.ConfigureServicesDelegate(serviceCollection);
            startup.ConfigureDelegate(app);

            var foo = app.ApplicationServices.GetRequiredService <StartupWithConfigureServices.IFoo>();

            Assert.True(foo.Invoked);
        }
예제 #11
0
        public void StartupClassAddsConfigureServicesToApplicationServices(string environment)
        {
            var services = new ServiceCollection().BuildServiceProvider();

            var diagnosticMessages = new List <string>();
            var hostingEnv         = new HostingEnvironment {
                EnvironmentName = environment
            };
            var loader  = new StartupLoader(services, hostingEnv);
            var type    = loader.FindStartupType("Microsoft.AspNet.Hosting.Tests", diagnosticMessages);
            var startup = loader.LoadMethods(type, diagnosticMessages);

            var app = new ApplicationBuilder(services);

            app.ApplicationServices = startup.ConfigureServicesDelegate(new ServiceCollection());
            startup.ConfigureDelegate(app);

            var options = app.ApplicationServices.GetRequiredService <IOptions <FakeOptions> >().Value;

            Assert.NotNull(options);
            Assert.True(options.Configured);
            Assert.Equal(environment, options.Environment);
        }
예제 #12
0
        private IServiceCollection BuildCommonServices()
        {
            // 应用根目录
            var rootPath = ResolveContentRootPath(string.Empty, AppContext.BaseDirectory);



            var services = new ServiceCollection();

            services.AddSingleton <GrpcHostOptions>(_options);
            services.AddSingleton <IConfiguration>(_config);

            services.AddTransient <IGrpcServerFactory, GrpcServerFactory>();
            services.AddOptions();
#if DEBUG
            services.AddLogging(logger => logger.SetMinimumLevel(LogLevel.Trace));
#else
            services.AddLogging();
#endif

            // Conjure up a RequestServices
            services.AddTransient <IStartupFilter, AutoRequestServicesStartupFilter>();
            services.AddTransient <IServiceProviderFactory <IServiceCollection>, DefaultServiceProviderFactory>();

            // Add GrpcContext
            services.AddScoped <GrpcContext>();
            // Aop 动态代理
            //services.AddInterception(builder => builder.SetDynamicProxyFactory());

            // 是否UseStartup
            if (!string.IsNullOrEmpty(_config[GrpcHostDefaults.StartupAssemblyKey]))
            {
                try
                {
                    var startupType = StartupLoader.FindStartupType(_config[GrpcHostDefaults.StartupAssemblyKey]);

                    if (typeof(IStartup).GetTypeInfo().IsAssignableFrom(startupType.GetTypeInfo()))
                    {
                        services.AddSingleton(typeof(IStartup), startupType);
                    }
                    else
                    {
                        services.AddSingleton(typeof(IStartup), sp =>
                        {
                            var methods = StartupLoader.LoadMethods(sp, startupType);
                            return(new ConventionBasedStartup(methods));
                        });
                    }
                }
                catch (Exception ex)
                {
                    var capture = ExceptionDispatchInfo.Capture(ex);
                    services.AddSingleton <IStartup>(_ =>
                    {
                        capture.Throw();
                        return(null);
                    });
                }
            }

            foreach (var configureServices in _configureServicesDelegates)
            {
                configureServices(_context, services);
            }

            return(services);
        }
예제 #13
0
        public void FindsStartupClassCaseInsensitive(string environment)
        {
            var type = StartupLoader.FindStartupType("Microsoft.AspNetCore.Hosting.Tests", environment);

            Assert.Equal("StartupCaseInsensitive", type.Name);
        }
예제 #14
0
    private IServiceCollection BuildCommonServices(out AggregateException?hostingStartupErrors)
    {
        hostingStartupErrors = null;

        _options = new WebHostOptions(_config, Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty);

        if (!_options.PreventHostingStartup)
        {
            var exceptions = new List <Exception>();
            var processed  = new HashSet <Assembly>();

            // Execute the hosting startup assemblies
            foreach (var assemblyName in _options.GetFinalHostingStartupAssemblies())
            {
                try
                {
                    var assembly = Assembly.Load(new AssemblyName(assemblyName));

                    if (!processed.Add(assembly))
                    {
                        // Already processed, skip it
                        continue;
                    }

                    foreach (var attribute in assembly.GetCustomAttributes <HostingStartupAttribute>())
                    {
                        var hostingStartup = (IHostingStartup)Activator.CreateInstance(attribute.HostingStartupType) !;
                        hostingStartup.Configure(this);
                    }
                }
                catch (Exception ex)
                {
                    // Capture any errors that happen during startup
                    exceptions.Add(new InvalidOperationException($"Startup assembly {assemblyName} failed to execute. See the inner exception for more details.", ex));
                }
            }

            if (exceptions.Count > 0)
            {
                hostingStartupErrors = new AggregateException(exceptions);
            }
        }

        var contentRootPath = ResolveContentRootPath(_options.ContentRootPath, AppContext.BaseDirectory);

        // Initialize the hosting environment
        ((IWebHostEnvironment)_hostingEnvironment).Initialize(contentRootPath, _options);
        _context.HostingEnvironment = _hostingEnvironment;

        var services = new ServiceCollection();

        services.AddSingleton(_options);
        services.AddSingleton <IWebHostEnvironment>(_hostingEnvironment);
        services.AddSingleton <IHostEnvironment>(_hostingEnvironment);
#pragma warning disable CS0618 // Type or member is obsolete
        services.AddSingleton <AspNetCore.Hosting.IHostingEnvironment>(_hostingEnvironment);
        services.AddSingleton <Extensions.Hosting.IHostingEnvironment>(_hostingEnvironment);
#pragma warning restore CS0618 // Type or member is obsolete
        services.AddSingleton(_context);

        var builder = new ConfigurationBuilder()
                      .SetBasePath(_hostingEnvironment.ContentRootPath)
                      .AddConfiguration(_config, shouldDisposeConfiguration: true);

        _configureAppConfigurationBuilder?.Invoke(_context, builder);

        var configuration = builder.Build();
        // register configuration as factory to make it dispose with the service provider
        services.AddSingleton <IConfiguration>(_ => configuration);
        _context.Configuration = configuration;

        services.TryAddSingleton(sp => new DiagnosticListener("Microsoft.AspNetCore"));
        services.TryAddSingleton <DiagnosticSource>(sp => sp.GetRequiredService <DiagnosticListener>());
        services.TryAddSingleton(sp => new ActivitySource("Microsoft.AspNetCore"));
        services.TryAddSingleton(DistributedContextPropagator.Current);

        services.AddTransient <IApplicationBuilderFactory, ApplicationBuilderFactory>();
        services.AddTransient <IHttpContextFactory, DefaultHttpContextFactory>();
        services.AddScoped <IMiddlewareFactory, MiddlewareFactory>();
        services.AddOptions();
        services.AddLogging();

        services.AddTransient <IServiceProviderFactory <IServiceCollection>, DefaultServiceProviderFactory>();

        if (!string.IsNullOrEmpty(_options.StartupAssembly))
        {
            try
            {
                var startupType = StartupLoader.FindStartupType(_options.StartupAssembly, _hostingEnvironment.EnvironmentName);

                if (typeof(IStartup).IsAssignableFrom(startupType))
                {
                    services.AddSingleton(typeof(IStartup), startupType);
                }
                else
                {
                    services.AddSingleton(typeof(IStartup), sp =>
                    {
                        var hostingEnvironment = sp.GetRequiredService <IHostEnvironment>();
                        var methods            = StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName);
                        return(new ConventionBasedStartup(methods));
                    });
                }
            }
            catch (Exception ex)
            {
                var capture = ExceptionDispatchInfo.Capture(ex);
                services.AddSingleton <IStartup>(_ =>
                {
                    capture.Throw();
                    return(null);
                });
            }
        }

        _configureServices?.Invoke(_context, services);

        return(services);
    }
예제 #15
0
        private IServiceCollection BuildCommonServices(out AggregateException hostingStartupErrors)
        {
            hostingStartupErrors = null;

            _options = new WebHostOptions(_config, Assembly.GetEntryAssembly()?.GetName().Name);

            if (!_options.PreventHostingStartup)
            {
                var exceptions = new List <Exception>();

                // Execute the hosting startup assemblies
                foreach (var assemblyName in _options.HostingStartupAssemblies)
                {
                    try
                    {
                        var assembly = Assembly.Load(new AssemblyName(assemblyName));

                        foreach (var attribute in assembly.GetCustomAttributes <HostingStartupAttribute>())
                        {
                            var hostingStartup = (IHostingStartup)Activator.CreateInstance(attribute.HostingStartupType);
                            hostingStartup.Configure(this);
                        }
                    }
                    catch (Exception ex)
                    {
                        // Capture any errors that happen during startup
                        exceptions.Add(new InvalidOperationException($"Startup assembly {assemblyName} failed to execute. See the inner exception for more details.", ex));
                    }
                }

                if (exceptions.Count > 0)
                {
                    hostingStartupErrors = new AggregateException(exceptions);
                }
            }

            var contentRootPath = ResolveContentRootPath(_options.ContentRootPath, AppContext.BaseDirectory);

            // Initialize the hosting environment
            var _hostingEnvironment = new HostingEnvironment
            {
                ContentRootPath = contentRootPath,
            };

            _context.HostingEnvironment = _hostingEnvironment;

            var services = new ServiceCollection();

            services.AddSingleton <IHostingEnvironment>(_hostingEnvironment);
            services.AddSingleton(_context);

            var builder = new ConfigurationBuilder()
                          .AddInMemoryCollection(_config.AsEnumerable());

            foreach (var configureAppConfiguration in _configureAppConfigurationBuilderDelegates)
            {
                configureAppConfiguration(_context, builder);
            }

            var configuration = builder.Build();

            services.AddSingleton <IConfiguration>(configuration);
            _context.Configuration = configuration;

            var listener = new DiagnosticListener("Microsoft.AspNetCore");

            services.AddSingleton <DiagnosticListener>(listener);
            services.AddSingleton <DiagnosticSource>(listener);

            services.AddTransient <IApplicationBuilderFactory, ApplicationBuilderFactory>();
            services.AddTransient <IHttpContextFactory, HttpContextFactory>();
            services.AddScoped <IMiddlewareFactory, MiddlewareFactory>();
            services.AddOptions();
            services.AddLogging();

            // Conjure up a RequestServices
            services.AddTransient <IStartupFilter, AutoRequestServicesStartupFilter>();
            services.AddTransient <IServiceProviderFactory <IServiceCollection>, DefaultServiceProviderFactory>();

            // Ensure object pooling is available everywhere.
            services.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();

            if (!string.IsNullOrEmpty(_options.StartupAssembly))
            {
                try
                {
                    var startupType = StartupLoader.FindStartupType(_options.StartupAssembly, _hostingEnvironment.EnvironmentName);

                    if (typeof(IStartup).GetTypeInfo().IsAssignableFrom(startupType.GetTypeInfo()))
                    {
                        services.AddSingleton(typeof(IStartup), startupType);
                    }
                    else
                    {
                        services.AddSingleton(typeof(IStartup), sp =>
                        {
                            var hostingEnvironment = sp.GetRequiredService <IHostingEnvironment>();
                            var methods            = StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName);
                            return(new ConventionBasedStartup(methods));
                        });
                    }
                }
                catch (Exception ex)
                {
                    var capture = ExceptionDispatchInfo.Capture(ex);
                    services.AddSingleton <IStartup>(_ =>
                    {
                        capture.Throw();
                        return(null);
                    });
                }
            }

            foreach (var configureServices in _configureServicesDelegates)
            {
                configureServices(_context, services);
            }

            return(services);
        }
예제 #16
0
    public GenericWebHostBuilder(IHostBuilder builder, WebHostBuilderOptions options)
    {
        _builder = builder;
        var configBuilder = new ConfigurationBuilder()
                            .AddInMemoryCollection();

        if (!options.SuppressEnvironmentConfiguration)
        {
            configBuilder.AddEnvironmentVariables(prefix: "ASPNETCORE_");
        }

        _config = configBuilder.Build();

        _builder.ConfigureHostConfiguration(config =>
        {
            config.AddConfiguration(_config);

            // We do this super early but still late enough that we can process the configuration
            // wired up by calls to UseSetting
            ExecuteHostingStartups();
        });

        // IHostingStartup needs to be executed before any direct methods on the builder
        // so register these callbacks first
        _builder.ConfigureAppConfiguration((context, configurationBuilder) =>
        {
            if (_hostingStartupWebHostBuilder != null)
            {
                var webhostContext = GetWebHostBuilderContext(context);
                _hostingStartupWebHostBuilder.ConfigureAppConfiguration(webhostContext, configurationBuilder);
            }
        });

        _builder.ConfigureServices((context, services) =>
        {
            var webhostContext = GetWebHostBuilderContext(context);
            var webHostOptions = (WebHostOptions)context.Properties[typeof(WebHostOptions)];

            // Add the IHostingEnvironment and IApplicationLifetime from Microsoft.AspNetCore.Hosting
            services.AddSingleton(webhostContext.HostingEnvironment);
#pragma warning disable CS0618 // Type or member is obsolete
            services.AddSingleton((AspNetCore.Hosting.IHostingEnvironment)webhostContext.HostingEnvironment);
            services.AddSingleton <IApplicationLifetime, GenericWebHostApplicationLifetime>();
#pragma warning restore CS0618 // Type or member is obsolete

            services.Configure <GenericWebHostServiceOptions>(options =>
            {
                // Set the options
                options.WebHostOptions = webHostOptions;
                // Store and forward any startup errors
                options.HostingStartupExceptions = _hostingStartupErrors;
            });

            // REVIEW: This is bad since we don't own this type. Anybody could add one of these and it would mess things up
            // We need to flow this differently
            services.TryAddSingleton(sp => new DiagnosticListener("Microsoft.AspNetCore"));
            services.TryAddSingleton <DiagnosticSource>(sp => sp.GetRequiredService <DiagnosticListener>());
            services.TryAddSingleton(sp => new ActivitySource("Microsoft.AspNetCore"));
            services.TryAddSingleton(DistributedContextPropagator.Current);

            services.TryAddSingleton <IHttpContextFactory, DefaultHttpContextFactory>();
            services.TryAddScoped <IMiddlewareFactory, MiddlewareFactory>();
            services.TryAddSingleton <IApplicationBuilderFactory, ApplicationBuilderFactory>();

            // IMPORTANT: This needs to run *before* direct calls on the builder (like UseStartup)
            _hostingStartupWebHostBuilder?.ConfigureServices(webhostContext, services);

            // Support UseStartup(assemblyName)
            if (!string.IsNullOrEmpty(webHostOptions.StartupAssembly))
            {
                try
                {
                    var startupType = StartupLoader.FindStartupType(webHostOptions.StartupAssembly, webhostContext.HostingEnvironment.EnvironmentName);
                    UseStartup(startupType, context, services);
                }
                catch (Exception ex) when(webHostOptions.CaptureStartupErrors)
                {
                    var capture = ExceptionDispatchInfo.Capture(ex);

                    services.Configure <GenericWebHostServiceOptions>(options =>
                    {
                        options.ConfigureApplication = app =>
                        {
                            // Throw if there was any errors initializing startup
                            capture.Throw();
                        };
                    });
                }
            }
        });
    }