Exemplo n.º 1
0
        public FabricContainer(ServiceCollection services = null)
        {
            services = services ?? new ServiceCollection();

            this.RegisterInstance <IServiceScopeInitializer>(this);

//#if NETCORE20

            this.AsFabricContainer().BuildServiceProvider(services);
//#else
//            this.AsFabricContainer().WithAspNetCoreServiceProvider();
//#endif

            var _hostingEnvironment = new HostingEnvironment();
            var _config             = new ConfigurationBuilder()
                                      .AddEnvironmentVariables(prefix: "ASPNETCORE_")
                                      .Build();
            var _options = new WebHostOptions(_config, Assembly.GetEntryAssembly()?.GetName().Name)
            {
            };
            // Microsoft.AspNetCore.Hosting.Internal.HostingEnvironmentExtensions.Initialize

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

            _hostingEnvironment.Initialize(contentRootPath, _options);
            this.RegisterInstance <IHostingEnvironment>(_hostingEnvironment);
        }
Exemplo n.º 2
0
        public override IWebHost Build()
        {
            var host = base.Build();

            _options2 = _options;
            return(host);
        }
Exemplo n.º 3
0
    internal static void Initialize(
        this IWebHostEnvironment hostingEnvironment,
        string contentRootPath,
        WebHostOptions options,
        IHostEnvironment?baseEnvironment = null)
    {
        if (options == null)
        {
            throw new ArgumentNullException(nameof(options));
        }
        if (string.IsNullOrEmpty(contentRootPath))
        {
            throw new ArgumentException("A valid non-empty content root must be provided.", nameof(contentRootPath));
        }
        if (!Directory.Exists(contentRootPath))
        {
            throw new ArgumentException($"The content root '{contentRootPath}' does not exist.", nameof(contentRootPath));
        }

        hostingEnvironment.ApplicationName         = baseEnvironment?.ApplicationName ?? options.ApplicationName;
        hostingEnvironment.ContentRootPath         = contentRootPath;
        hostingEnvironment.ContentRootFileProvider = baseEnvironment?.ContentRootFileProvider ?? new PhysicalFileProvider(hostingEnvironment.ContentRootPath);

        var webRoot = options.WebRoot;

        if (webRoot == null)
        {
            // Default to /wwwroot if it exists.
            var wwwroot = Path.Combine(hostingEnvironment.ContentRootPath, "wwwroot");
            if (Directory.Exists(wwwroot))
            {
                hostingEnvironment.WebRootPath = wwwroot;
            }
        }
        else
        {
            hostingEnvironment.WebRootPath = Path.Combine(hostingEnvironment.ContentRootPath, webRoot);
        }

        if (!string.IsNullOrEmpty(hostingEnvironment.WebRootPath))
        {
            hostingEnvironment.WebRootPath = Path.GetFullPath(hostingEnvironment.WebRootPath);
            if (!Directory.Exists(hostingEnvironment.WebRootPath))
            {
                Directory.CreateDirectory(hostingEnvironment.WebRootPath);
            }
            hostingEnvironment.WebRootFileProvider = new PhysicalFileProvider(hostingEnvironment.WebRootPath);
        }
        else
        {
            hostingEnvironment.WebRootFileProvider = new NullFileProvider();
        }

        hostingEnvironment.EnvironmentName =
            baseEnvironment?.EnvironmentName ??
            options.Environment ??
            hostingEnvironment.EnvironmentName;
    }
Exemplo n.º 4
0
        private static IHostingEnvironment InitializeEnvironment()
        {
            IConfigurationRoot config = new ConfigurationBuilder().AddEnvironmentVariables("ASPNETCORE_").Build();
            var options = new WebHostOptions(config, GetApplicationName());
            var env     = new HostingEnvironment();

            env.Initialize(AppContext.BaseDirectory, options);
            return(env);
        }
Exemplo n.º 5
0
        public override IWebHost Build()
        {
            var host = base.Build();

            _options2 = _options;
            //_options.CaptureStartupErrors = true;
            //_options.SuppressStatusMessages = false;
            return(host);
        }
        public void ReadsOldEnvKey()
        {
            var parameters = new Dictionary <string, string>()
            {
                { "ENVIRONMENT", "Development" }
            };
            var config = new WebHostOptions(new ConfigurationBuilder().AddInMemoryCollection(parameters).Build());

            Assert.Equal("Development", config.Environment);
        }
Exemplo n.º 7
0
    public void ReadsOldEnvKey()
    {
        var parameters = new Dictionary <string, string>()
        {
            { "ENVIRONMENT", Environments.Development }
        };
        var config = new WebHostOptions(new ConfigurationBuilder().AddInMemoryCollection(parameters).Build(), applicationNameFallback: null);

        Assert.Equal(Environments.Development, config.Environment);
    }
Exemplo n.º 8
0
    public void AllowsNumberForDetailedErrors(string value, bool expected)
    {
        var parameters = new Dictionary <string, string>()
        {
            { "detailedErrors", value }
        };
        var config = new WebHostOptions(new ConfigurationBuilder().AddInMemoryCollection(parameters).Build(), applicationNameFallback: null);

        Assert.Equal(expected, config.DetailedErrors);
    }
Exemplo n.º 9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.Filters.AddService(typeof(ApiExplorerDataFilter));
            });
            services.AddSingleton <ApiExplorerDataFilter>();

            var hostingEnvironment = services.BuildServiceProvider().GetService <IHostingEnvironment>();
            var webHostOptions     = new WebHostOptions(Configuration);
        }
Exemplo n.º 10
0
        private static IHostingEnvironment GetHostingEnvironment(Func <string> contentRootPath)
        {
            var hostingEnvironment = new HostingEnvironment();

            var webHostOptions = new WebHostOptions();

            hostingEnvironment.Initialize("Template", contentRootPath(), webHostOptions);

            hostingEnvironment.EnvironmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            return(hostingEnvironment);
        }
Exemplo n.º 11
0
 public ConsoleApp(
     IServiceCollection appServices,
     IServiceProvider hostingServiceProvider,
     IConfiguration config,
     WebHostOptions options,
     AggregateException hostingStartupErrors)
 {
     _config = config;
     _hostingStartupErrors = hostingStartupErrors;
     _options = options;
     _applicationServiceCollection = appServices;
     _hostingServiceProvider       = hostingServiceProvider;
     _startup = _hostingServiceProvider.GetService <IConsoleStartup>();
 }
Exemplo n.º 12
0
 public SmallWebHost(IServiceProvider provider,
                     IConfiguration config,
                     Microsoft.Extensions.Hosting.IApplicationLifetime applicationLifetime,
                     ILogger <SmallWebHost> logger,
                     WebHostOptions options,
                     Action <IApplicationBuilder> appFuncBuilder)
 {
     Services             = provider;
     _config              = config;
     _options             = options;
     _logger              = logger;
     _applicationLifetime = applicationLifetime as Microsoft.Extensions.Hosting.Internal.ApplicationLifetime;
     _appFuncBuilder      = appFuncBuilder;
 }
        private IServiceCollection BuildCommonServices(out AggregateException hostingStartupErrors)
        {
            hostingStartupErrors = null;

            _options = new WebHostOptions(_config);

            var services = new ServiceCollection();


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

            Environment.Initialize(Assembly.GetEntryAssembly()?.GetName().Name, contentRootPath, _options);

            _context.HostingEnvironment = Environment;

            services.AddSingleton <IHostingEnvironment>(Environment);


            var builder = new ConfigurationBuilder()
                          .SetBasePath(Environment.ContentRootPath)
                          .AddConfiguration(_config);

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

            var configuration = builder.Build();

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

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

            services.AddOptions();

            services.AddLogging();


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

            return(services);
        }
Exemplo n.º 14
0
    private void ExecuteHostingStartups()
    {
        var webHostOptions = new WebHostOptions(_config);

        if (webHostOptions.PreventHostingStartup)
        {
            return;
        }

        var exceptions = new List <Exception>();
        var processed  = new HashSet <Assembly>();

        _hostingStartupWebHostBuilder = new HostingStartupWebHostBuilder(this);

        // Execute the hosting startup assemblies
        foreach (var assemblyName in webHostOptions.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(_hostingStartupWebHostBuilder);
                }
            }
            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);
        }
    }
Exemplo n.º 15
0
    public WebHost(
        IServiceCollection appServices,
        IServiceProvider hostingServiceProvider,
        WebHostOptions options,
        IConfiguration config,
        AggregateException?hostingStartupErrors)
    {
        if (appServices == null)
        {
            throw new ArgumentNullException(nameof(appServices));
        }

        if (hostingServiceProvider == null)
        {
            throw new ArgumentNullException(nameof(hostingServiceProvider));
        }

        if (config == null)
        {
            throw new ArgumentNullException(nameof(config));
        }

        _config = config;
        _hostingStartupErrors = hostingStartupErrors;
        _options = options;
        _applicationServiceCollection = appServices;
        _hostingServiceProvider       = hostingServiceProvider;
        _applicationServiceCollection.AddSingleton <ApplicationLifetime>();
        // There's no way to to register multiple service types per definition. See https://github.com/aspnet/DependencyInjection/issues/360
#pragma warning disable CS8634 // The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'class' constraint.
        _applicationServiceCollection.AddSingleton(services
                                                   => services.GetService <ApplicationLifetime>() as IHostApplicationLifetime);
#pragma warning disable CS0618 // Type or member is obsolete
        _applicationServiceCollection.AddSingleton(services
                                                   => services.GetService <ApplicationLifetime>() as AspNetCore.Hosting.IApplicationLifetime);
        _applicationServiceCollection.AddSingleton(services
                                                   => services.GetService <ApplicationLifetime>() as Extensions.Hosting.IApplicationLifetime);
#pragma warning restore CS0618 // Type or member is obsolete
#pragma warning restore CS8634 // The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'class' constraint.
        _applicationServiceCollection.AddSingleton <HostedServiceExecutor>();
    }
Exemplo n.º 16
0
        public static IHostBuilder AddKestrelApp(this IHostBuilder builder, Action <IApplicationBuilder> appBuilder)
        {
            builder.ConfigureServices(services =>
            {
                var sp = services.BuildServiceProvider();

                var appLifetime = ActivatorUtilities.CreateInstance <ApplicationLifetime>(sp);
                services.AddSingleton <Microsoft.AspNetCore.Hosting.IApplicationLifetime>(appLifetime);
                services.AddSingleton <Microsoft.Extensions.Hosting.IApplicationLifetime>(appLifetime);

                var hostOptions = new WebHostOptions(sp.GetRequiredService <IConfiguration>(), Assembly.GetEntryAssembly()?.GetName().Name);

                var commonHosting = new HostingEnvironment();
                commonHosting.Initialize(sp.GetRequiredService <Microsoft.Extensions.Hosting.IHostingEnvironment>(), hostOptions);
                services.AddSingleton <Microsoft.AspNetCore.Hosting.IHostingEnvironment>(commonHosting);
                services.AddSingleton <Microsoft.Extensions.Hosting.IHostingEnvironment>(commonHosting);

                var listener = new DiagnosticListener("Microsoft.AspNetCore");
                services.AddSingleton <DiagnosticListener>(listener);
                services.AddSingleton <DiagnosticSource>(listener);

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

                services.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();

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

                services.TryAddSingleton <ITransportFactory, LibuvTransportFactory>();

                services.AddTransient <IConfigureOptions <KestrelServerOptions>, KestrelServerOptionsSetup>();
                services.AddSingleton <IServer, KestrelServer>();

                services.AddSingleton(provider => ConstructWebHost(provider, hostOptions, appBuilder));
                services.AddSingleton <IHostedService, HttpHostedService>();
            });

            return(builder);
        }
Exemplo n.º 17
0
        public void ReadsParametersCorrectly()
        {
            var parameters = new Dictionary <string, string>()
            {
                { "webroot", "wwwroot" },
                { "server", "Microsoft.AspNetCore.Server.Kestrel" },
                { "application", "MyProjectReference" },
                { "environment", "Development" },
                { "detailederrors", "true" },
                { "captureStartupErrors", "true" }
            };

            var config = new WebHostOptions(new ConfigurationBuilder().AddInMemoryCollection(parameters).Build());

            Assert.Equal("wwwroot", config.WebRoot);
            Assert.Equal("Microsoft.AspNetCore.Server.Kestrel", config.ServerAssembly);
            Assert.Equal("MyProjectReference", config.Application);
            Assert.Equal("Development", config.Environment);
            Assert.True(config.CaptureStartupErrors);
            Assert.True(config.DetailedErrors);
        }
Exemplo n.º 18
0
    private static WebHostBuilderContext GetWebHostBuilderContext(HostBuilderContext context)
    {
        if (!context.Properties.TryGetValue(typeof(WebHostBuilderContext), out var contextVal))
        {
            var options = new WebHostOptions(context.Configuration, Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty);
            var webHostBuilderContext = new WebHostBuilderContext
            {
                Configuration      = context.Configuration,
                HostingEnvironment = new HostingEnvironment(),
            };
            webHostBuilderContext.HostingEnvironment.Initialize(context.HostingEnvironment.ContentRootPath, options);
            context.Properties[typeof(WebHostBuilderContext)] = webHostBuilderContext;
            context.Properties[typeof(WebHostOptions)]        = options;
            return(webHostBuilderContext);
        }

        // Refresh config, it's periodically updated/replaced
        var webHostContext = (WebHostBuilderContext)contextVal;

        webHostContext.Configuration = context.Configuration;
        return(webHostContext);
    }
Exemplo n.º 19
0
    public WebHost(
        IServiceCollection appServices,
        IServiceProvider hostingServiceProvider,
        WebHostOptions options,
        IConfiguration config,
        AggregateException?hostingStartupErrors)
    {
        if (appServices == null)
        {
            throw new ArgumentNullException(nameof(appServices));
        }

        if (hostingServiceProvider == null)
        {
            throw new ArgumentNullException(nameof(hostingServiceProvider));
        }

        if (config == null)
        {
            throw new ArgumentNullException(nameof(config));
        }

        _config = config;
        _hostingStartupErrors = hostingStartupErrors;
        _options = options;
        _applicationServiceCollection = appServices;
        _hostingServiceProvider       = hostingServiceProvider;
        _applicationServiceCollection.AddSingleton <ApplicationLifetime>();
        // There's no way to to register multiple service types per definition. See https://github.com/aspnet/DependencyInjection/issues/360
        _applicationServiceCollection.AddSingleton <IHostApplicationLifetime>(services
                                                                              => services.GetService <ApplicationLifetime>() !);
#pragma warning disable CS0618 // Type or member is obsolete
        _applicationServiceCollection.AddSingleton <AspNetCore.Hosting.IApplicationLifetime>(services
                                                                                             => services.GetService <ApplicationLifetime>() !);
        _applicationServiceCollection.AddSingleton <Extensions.Hosting.IApplicationLifetime>(services
                                                                                             => services.GetService <ApplicationLifetime>() !);
#pragma warning restore CS0618 // Type or member is obsolete
        _applicationServiceCollection.AddSingleton <HostedServiceExecutor>();
    }
Exemplo n.º 20
0
    public void ReadsParametersCorrectly()
    {
        var parameters = new Dictionary <string, string>()
        {
            { WebHostDefaults.WebRootKey, "wwwroot" },
            { WebHostDefaults.ApplicationKey, "MyProjectReference" },
            { WebHostDefaults.StartupAssemblyKey, "MyProjectReference" },
            { WebHostDefaults.EnvironmentKey, Environments.Development },
            { WebHostDefaults.DetailedErrorsKey, "true" },
            { WebHostDefaults.CaptureStartupErrorsKey, "true" },
            { WebHostDefaults.SuppressStatusMessagesKey, "true" }
        };

        var config = new WebHostOptions(new ConfigurationBuilder().AddInMemoryCollection(parameters).Build(), applicationNameFallback: null);

        Assert.Equal("wwwroot", config.WebRoot);
        Assert.Equal("MyProjectReference", config.ApplicationName);
        Assert.Equal("MyProjectReference", config.StartupAssembly);
        Assert.Equal(Environments.Development, config.Environment);
        Assert.True(config.CaptureStartupErrors);
        Assert.True(config.DetailedErrors);
        Assert.True(config.SuppressStatusMessages);
    }
Exemplo n.º 21
0
    private WebHostBuilderContext GetWebHostBuilderContext(HostBuilderContext context)
    {
        if (!context.Properties.TryGetValue(typeof(WebHostBuilderContext), out var contextVal))
        {
            // Use _config as a fallback for WebHostOptions in case the chained source was removed from the hosting IConfigurationBuilder.
            var options = new WebHostOptions(context.Configuration, fallbackConfiguration: _config);
            var webHostBuilderContext = new WebHostBuilderContext
            {
                Configuration      = context.Configuration,
                HostingEnvironment = new HostingEnvironment(),
            };
            webHostBuilderContext.HostingEnvironment.Initialize(context.HostingEnvironment.ContentRootPath, options);
            context.Properties[typeof(WebHostBuilderContext)] = webHostBuilderContext;
            context.Properties[typeof(WebHostOptions)]        = options;
            return(webHostBuilderContext);
        }

        // Refresh config, it's periodically updated/replaced
        var webHostContext = (WebHostBuilderContext)contextVal;

        webHostContext.Configuration = context.Configuration;
        return(webHostContext);
    }
Exemplo n.º 22
0
 private static IWebHost ConstructWebHost(IServiceProvider sp, WebHostOptions hostOptions, Action <IApplicationBuilder> appBuilder)
 {
     return(ActivatorUtilities.CreateInstance(sp, typeof(SmallWebHost), hostOptions, appBuilder) as IWebHost);
 }
Exemplo n.º 23
0
        public static Microsoft.AspNetCore.Hosting.IHostingEnvironment Initialize(this Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment, Microsoft.Extensions.Hosting.IHostingEnvironment baseEnv, WebHostOptions options)
        {
            hostingEnvironment.ApplicationName         = options.ApplicationName;
            hostingEnvironment.ContentRootPath         = baseEnv.ContentRootPath;
            hostingEnvironment.ContentRootFileProvider = new PhysicalFileProvider(hostingEnvironment.ContentRootPath);

            var webRoot = options.WebRoot;

            if (webRoot == null)
            {
                // Default to /wwwroot if it exists.
                var wwwroot = Path.Combine(hostingEnvironment.ContentRootPath, "wwwroot");
                if (Directory.Exists(wwwroot))
                {
                    hostingEnvironment.WebRootPath = wwwroot;
                }
            }
            else
            {
                hostingEnvironment.WebRootPath = Path.Combine(hostingEnvironment.ContentRootPath, webRoot);
            }

            if (!string.IsNullOrEmpty(hostingEnvironment.WebRootPath))
            {
                hostingEnvironment.WebRootPath = Path.GetFullPath(hostingEnvironment.WebRootPath);
                if (!Directory.Exists(hostingEnvironment.WebRootPath))
                {
                    Directory.CreateDirectory(hostingEnvironment.WebRootPath);
                }
                hostingEnvironment.WebRootFileProvider = new PhysicalFileProvider(hostingEnvironment.WebRootPath);
            }
            else
            {
                hostingEnvironment.WebRootFileProvider = new NullFileProvider();
            }

            hostingEnvironment.EnvironmentName =
                options.Environment ??
                hostingEnvironment.EnvironmentName;

            return(hostingEnvironment);
        }
Exemplo n.º 24
0
        private static async Task RunAsync(string[] args, CancellationToken token)
        {
            args[2] = args[2].Replace("^>", ">").Replace("^<", "<");;



            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                          .AddEnvironmentVariables();
            var config = builder.Build();


            var _options       = new WebHostOptions(config);
            var appEnvironment = PlatformServices.Default.Application;

            var applicationName = _options.ApplicationName ?? appEnvironment.ApplicationName;

            var environment = new HostingEnvironment();

            environment.Initialize(applicationName, Directory.GetCurrentDirectory(), _options);


            var url      = "http://localhost:5000";
            var basePath = environment.IsProduction() ?
                           environment.ContentRootPath
                   : Path.Combine(environment.ContentRootPath, "artifacts", "app");


            using (var host = new WebHostBuilder()
                              .UseKestrel()
                              .UseConfiguration(config)
                              .UseUrls(url)
                              .UseWebRoot(basePath)
                              .UseContentRoot(Directory.GetCurrentDirectory())
                              .ConfigureLogging(l => l.AddConsole(config.GetSection("Logging")))
                              .ConfigureServices(ConfigureServices)
                              .Configure(app =>
            {
                // to do - wire in our HTTP endpoints

                app.UseStaticFiles();
                app.UseWebPages();
            })
                              .Build())
            {
                host.Start();// (token); //.Run(token);


                var result = await RequireJS.RunAsync <object, string>(host.Services.GetService <INodeServices>(), basePath.Replace("\\", "/"), "AppInsightsQueryReporter", url, new
                {
                    appId  = args[0],
                    appKey = args[1],
                    query  = args[2]
                });

                Console.WriteLine(result.ToString());



                //   await Task.Delay(Timeout.Infinite, token);
            }
        }
Exemplo n.º 25
0
        internal ServiceRegistry CompileConfigurationAndServicesForIdiomaticBootstrapping()
        {
            _baseServices.Insert(0, ServiceDescriptor.Singleton <IHostedService, MessagingActivator>());

            // Add services
            var options         = new WebHostOptions(EnvironmentConfiguration);
            var contentRootPath = ResolveContentRootPath(options.ContentRootPath, AppContext.BaseDirectory);

            // Initialize the hosting environment
            // TODO -- Watch this, if there are bugs in bootstrapping!!!!!!
            _hostingEnvironment.Initialize(contentRootPath, options);
            _hostingEnvironment.ApplicationName = ApplicationAssembly.FullName;

            var context = new WebHostBuilderContext
            {
                Configuration      = EnvironmentConfiguration,
                HostingEnvironment = _hostingEnvironment
            };

            Services.AddSingleton(_hostingEnvironment);
            Services.AddSingleton(context);

            var builder = Configuration
                          .SetBasePath(_hostingEnvironment.ContentRootPath)
                          .AddInMemoryCollection(EnvironmentConfiguration.AsEnumerable());

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

            var configuration = builder.Build();

            Services.AddSingleton <IConfiguration>(configuration);
            Services.AddSingleton <IConfigurationRoot>(configuration);

            context.Configuration = configuration;


            Settings.Bootstrap(new WebHostBuilderContext
            {
                HostingEnvironment = _hostingEnvironment,
                Configuration      = configuration
            });

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

            Services.AddSingleton(listener);
            Services.AddSingleton <DiagnosticSource>(listener);

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

            Services.AddSingleton <Microsoft.AspNetCore.Hosting.IApplicationLifetime, ApplicationLifetime>();

            // Conjure up a RequestServices
            // TODO -- want this to be optional
            Services.AddTransient <IStartupFilter, AutoRequestServicesStartupFilter>();

            foreach (var configureServices in _configureServicesDelegates)
            {
                configureServices(context, Services);
            }

            var all = _baseServices.Concat(ExtensionServices).Concat(_applicationServices);

            var combined = new ServiceRegistry();

            combined.AddRange(all);

            combined.For <IDurableMessagingFactory>().UseIfNone <NulloDurableMessagingFactory>();
            combined.For <IServer>().UseIfNone <NulloServer>();

            return(combined);
        }
Exemplo n.º 26
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        /// <param name="logDirectory">log file path
        /// <para>e.g. .Logs or wwwroor/logs or C:/wwwroot/logs</para>
        /// </param>
        public static void AddFileLog(this IServiceCollection services, string logDirectory = ".Logs")
        {
            if (!services.Any(x => x.ImplementationType == typeof(LOG.LoggerFactory)))
            {
                LOG.LoggerFactory.ServiceCollection = services;
                if (string.IsNullOrEmpty(logDirectory))
                {
                    logDirectory = ".Logs";
                }
                services.AddHttpContextAccessor();
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                Console.OutputEncoding = System.Text.Encoding.UTF8;
                var _config = services.FirstOrDefault(x => x.ServiceType == typeof(IConfiguration))?.ImplementationInstance as IConfiguration;
                if (_config == null)
                {
                    _config = new ConfigurationBuilder()
                              .AddEnvironmentVariables("ASPNETCORE_")
                              .SetBasePath(AppContext.BaseDirectory)
                              .Build();
                    _config[WebHostDefaults.ContentRootKey] = AppContext.BaseDirectory;
                    services.AddSingleton(_config);
                }
                if (string.IsNullOrEmpty(_config[WebHostDefaults.ContentRootKey]))
                {
                    _config[WebHostDefaults.ContentRootKey] = AppContext.BaseDirectory;
                }

                IHostingEnvironment environment = (IHostingEnvironment)services.FirstOrDefault(x => x.ServiceType == typeof(IHostingEnvironment))
                                                  ?.ImplementationInstance;
                if (environment == null)
                {
                    WebHostOptions options = new WebHostOptions(_config, Assembly.GetEntryAssembly().GetName().Name);
                    environment = new HostingEnvironment();
                    environment.Initialize(AppContext.BaseDirectory, options);
                    services.TryAddSingleton <IHostingEnvironment>(environment);
                }
                if (string.IsNullOrEmpty(environment.WebRootPath))
                {
                    var _contentPath = _config[WebHostDefaults.ContentRootKey];
                    var binIndex     = _contentPath.LastIndexOf("\\bin\\");
                    if (binIndex > -1)
                    {
                        var contentPath = _contentPath.Substring(0, binIndex);
                        if (contentPath.IndexOf(environment.ApplicationName) > -1)
                        {
                            _config[WebHostDefaults.ContentRootKey] = contentPath;
                            environment.ContentRootPath             = contentPath;
                            environment.WebRootPath = System.IO.Path.Combine(contentPath, "wwwroot");
                        }
                    }
                    else
                    {
                        environment.WebRootPath = System.IO.Path.Combine(_config["ContentRoot"], "wwwroot");
                    }
                }
                if (Path.IsPathRooted(logDirectory))
                {
                    LoggerSettings.LogDirectory = logDirectory;
                }
                else
                {
                    LoggerSettings.LogDirectory = Path.Combine(_config["ContentRoot"], logDirectory);
                }
                if (!Directory.Exists(LoggerSettings.LogDirectory))
                {
                    Directory.CreateDirectory(LoggerSettings.LogDirectory);
                }
                var path = Path.Combine(LoggerSettings.LogDirectory, LoggerSettings.LogJsonFileName);
                if (!File.Exists(path))
                {
                    File.AppendAllText(path, LoggerSettings.LoggingJsonContent);
                }
                ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
                configurationBuilder
                .SetBasePath(environment.ContentRootPath)
                .AddJsonFile(path, true, true);
                var configuration = configurationBuilder.Build();
                services.RemoveAll <ILoggerProviderConfigurationFactory>();
                services.RemoveAll(typeof(ILoggerProviderConfiguration <>));


                var type = typeof(ILoggerProviderConfigurationFactory).Assembly.DefinedTypes
                           .SingleOrDefault(t => t.Name == "LoggingConfiguration");
                services.RemoveAll(type);

                services.AddLogging(x =>
                {
                    x.AddConfiguration(configuration);
                    if (!x.Services.Any(t => t.ServiceType == typeof(ILoggerProvider)))
                    {
                        x.AddConsole();
                    }
                    x.Services.RemoveAll <IConfigureOptions <Logging.LoggerFilterOptions> >();
                    x.Services.AddSingleton <IConfigureOptions <Logging.LoggerFilterOptions> >(new LOG.LoggerFilterConfigureOptions(configuration));
                });
                services.Replace(ServiceDescriptor.Singleton <ILoggerFactory, LOG.LoggerFactory>());
            }
        }
Exemplo n.º 27
0
    private void ScanAssemblyAndRegisterStartup(HostBuilderContext context, IServiceCollection services, WebHostBuilderContext webhostContext, WebHostOptions webHostOptions)
    {
        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();
                };
            });
        }
    }
Exemplo n.º 28
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        /// <param name="logAction">logAction</param>
        /// <para>e.g. .Logs or wwwroor/logs or C:/wwwroot/logs</para>
        public static IServiceCollection AddFileLog(this IServiceCollection services, Action <LogOptions> logAction = null)
        {
            bool flag = !services.Any((ServiceDescriptor x) => x.ImplementationType == typeof(LoggerFactory));

            if (flag)
            {
                LogOptions logOptions = new LogOptions();
                if (logAction != null)
                {
                    logAction(logOptions);
                }
                services.Replace(ServiceDescriptor.Transient <IApplicationBuilderFactory, DefaultApplicationBuilderFactory>());
                LoggerSettings.Format           = logOptions.Format;
                LoggerFactory.ServiceCollection = services;
                bool flag2 = string.IsNullOrEmpty(logOptions.LogDirectory);
                if (flag2)
                {
                    logOptions.LogDirectory = ".Logs";
                }
                services.AddHttpContextAccessor();
                services.AddSingleton <ILogAdapter, FileLogAdapter>();
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                Console.OutputEncoding = Encoding.UTF8;
                ServiceDescriptor serviceDescriptor = services.FirstOrDefault((ServiceDescriptor x) => x.ServiceType == typeof(IConfiguration));
                IConfiguration    _config           = ((serviceDescriptor != null) ? serviceDescriptor.ImplementationInstance : null) as IConfiguration;
                bool flag3 = _config == null;
                if (flag3)
                {
                    _config = FileConfigurationExtensions.SetBasePath(EnvironmentVariablesExtensions.AddEnvironmentVariables(new ConfigurationBuilder(), "ASPNETCORE_"), AppContext.BaseDirectory).Build();
                    _config[WebHostDefaults.ContentRootKey] = AppContext.BaseDirectory;
                    services.AddSingleton(_config);
                }
                bool flag4 = string.IsNullOrEmpty(_config[WebHostDefaults.ContentRootKey]);
                if (flag4)
                {
                    _config[WebHostDefaults.ContentRootKey] = AppContext.BaseDirectory;
                }
                ServiceDescriptor   serviceDescriptor2 = services.FirstOrDefault((ServiceDescriptor x) => x.ServiceType == typeof(IHostingEnvironment));
                IHostingEnvironment environment        = (IHostingEnvironment)((serviceDescriptor2 != null) ? serviceDescriptor2.ImplementationInstance : null);
                bool flag5 = environment == null;
                if (flag5)
                {
                    WebHostOptions options = new WebHostOptions(_config, Assembly.GetEntryAssembly().GetName().Name);
                    environment = new HostingEnvironment();
                    HostingEnvironmentExtensions.Initialize(environment, AppContext.BaseDirectory, options);
                    services.TryAddSingleton(environment);
                }
                bool flag6 = string.IsNullOrEmpty(environment.WebRootPath);
                if (flag6)
                {
                    string _contentPath = _config[WebHostDefaults.ContentRootKey];
                    int    binIndex     = _contentPath.LastIndexOf("\\bin\\");
                    bool   flag7        = binIndex > -1;
                    if (flag7)
                    {
                        string contentPath = _contentPath.Substring(0, binIndex);
                        bool   flag8       = contentPath.IndexOf(environment.ApplicationName) > -1;
                        if (flag8)
                        {
                            _config[WebHostDefaults.ContentRootKey] = contentPath;
                            environment.ContentRootPath             = contentPath;
                            environment.WebRootPath = Path.Combine(contentPath, "wwwroot");
                        }
                        else
                        {
                            environment.WebRootPath = _contentPath;
                        }
                    }
                    else
                    {
                        environment.WebRootPath = Path.Combine(_config["ContentRoot"], "wwwroot");
                    }
                }
                bool flag9 = Path.IsPathRooted(logOptions.LogDirectory);
                if (flag9)
                {
                    LoggerSettings.LogDirectory = logOptions.LogDirectory;
                }
                else
                {
                    LoggerSettings.LogDirectory = Path.Combine(_config["ContentRoot"], logOptions.LogDirectory);
                }
                bool flag10 = !Directory.Exists(LoggerSettings.LogDirectory);
                if (flag10)
                {
                    Directory.CreateDirectory(LoggerSettings.LogDirectory);
                }
                string path   = Path.Combine(LoggerSettings.LogDirectory, "_logging.json");
                bool   flag11 = !File.Exists(path);
                if (flag11)
                {
                    File.AppendAllText(path, "{\"Rules\":[{\"CategoryName\":\"Default\",\"LogLevel\":\"Information\",\"LogType\":\"All\",\"TraceCount\":5}]}");
                }
                ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
                JsonConfigurationExtensions.AddJsonFile(FileConfigurationExtensions.SetBasePath(configurationBuilder, environment.ContentRootPath), path, true, true);
                IConfigurationRoot configuration = configurationBuilder.Build();
                services.RemoveAll <ILoggerProviderConfigurationFactory>();
                services.RemoveAll(typeof(ILoggerProviderConfiguration <>));
                TypeInfo type = typeof(ILoggerProviderConfigurationFactory).Assembly.DefinedTypes.SingleOrDefault((TypeInfo t) => t.Name == "LoggingConfiguration");
                services.RemoveAll(type);

                LoggingServiceCollectionExtensions.AddLogging(services, delegate(ILoggingBuilder x)
                {
                    x.AddConfiguration(configuration);
                    //bool flag13 = !x.Services.Any((ServiceDescriptor t) => t.ServiceType == typeof(ILoggerProvider));
                    //if (flag13)
                    //{
                    //    ConsoleLoggerExtensions.AddConsole(x);
                    //}
                    x.Services.RemoveAll <IConfigureOptions <LoggerFilterOptions> >();
                    x.Services.AddSingleton(new LoggerFilterConfigureOptions(configuration));
                });
                services.Replace(ServiceDescriptor.Singleton <ILoggerFactory, LoggerFactory>());
                services.Replace(ServiceDescriptor.Singleton <DiagnosticSource>(new DefaultDiagnosticListener()));
                bool flag12 = services.IsHttpRequest();
                if (flag12)
                {
                    MarkdownFileMiddleware.SaveResourceFiles(environment.WebRootPath);
                }
                DefaultApplicationBuilderFactory.OnCreateBuilder(new Action <IApplicationBuilder, object>(LoggerExtensions.UseFileLog), logOptions);
            }
            return(services);
        }
Exemplo n.º 29
0
 public WebHostBuilderWrap() : base()
 {
     _options2 = new WebHostOptions(_config, Assembly.GetEntryAssembly()?.GetName().Name);
 }