Пример #1
0
        public void EnvDefaultsToDevelopmentConfigValueIfSpecified()
        {
            var vals = new Dictionary<string, string>
            {
                { "ASPNET_ENV", "Staging" }
            };

            var config = new Configuration()
                .Add(new MemoryConfigurationSource(vals));

            var context = new HostingContext
            {
                ServerFactory = this,
                Configuration = config
            };

            var engine = new HostingEngine();

            using (engine.Start(context))
            {
                Assert.Equal("Staging", context.EnvironmentName);
                var env = context.ApplicationServices.GetRequiredService<IHostingEnvironment>();
                Assert.Equal("Staging", env.EnvironmentName);
            }
        }
Пример #2
0
        public IDisposable Start(HostingContext context)
        {
            EnsureContextDefaults(context);
            EnsureApplicationServices(context);
            EnsureBuilder(context);
            EnsureServerFactory(context);
            InitalizeServerFactory(context);
            EnsureApplicationDelegate(context);

            var contextFactory = context.ApplicationServices.GetRequiredService<IHttpContextFactory>();
            var contextAccessor = context.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
            var server = context.ServerFactory.Start(context.Server,
                features =>
                {
                    var httpContext = contextFactory.CreateHttpContext(features);
                    contextAccessor.HttpContext = httpContext;
                    return context.ApplicationDelegate(httpContext);
                });

            return new Disposable(() =>
            {
                _appLifetime.NotifyStopping();
                server.Dispose();
                _appLifetime.NotifyStopped();
            });
        }
Пример #3
0
        public Task<int> Main(string[] args)
        {
            //Add command line configuration source to read command line parameters.
            var config = new Configuration();
            config.AddCommandLine(args);

            var serviceCollection = new ServiceCollection();
            serviceCollection.Add(HostingServices.GetDefaultServices(config));
            var services = serviceCollection.BuildServiceProvider(_hostServiceProvider);

            var context = new HostingContext()
            {
                Services = services,
                Configuration = config,
                ServerName = "Microsoft.AspNet.Server.WebListener",
                ApplicationName = "BugTracker"
            };

            var engine = services.GetService<IHostingEngine>();
            if (engine == null)
            {
                throw new Exception("TODO: IHostingEngine service not available exception");
            }

            using (engine.Start(context))
            {
                Console.WriteLine("Started the server..");
                Console.WriteLine("Press any key to stop the server");
                Console.ReadLine();
            }
            return Task.FromResult(0);
        }
Пример #4
0
        // REVIEW: we can configure services via AppStartup or via hostContext.Services
        public TestServer(IConfiguration config, IServiceProvider serviceProvider, Action<IApplicationBuilder> configureApp, ConfigureServicesDelegate configureServices)
        {
            var hostContext = new HostingContext()
            {
                ApplicationName = "Test App",
                Configuration = config,
                ServerFactory = this,
                StartupMethods = new StartupMethods(configureApp, configureServices)
            };

            _appInstance = new HostingEngine(serviceProvider).Start(hostContext);
        }
Пример #5
0
        public void ApplicationNameDefaultsToApplicationEnvironmentName()
        {
            var context = new HostingContext
            {
                ServerFactory = this
            };

            var engine = new HostingEngine();

            using (engine.Start(context))
            {
                Assert.Equal("Microsoft.AspNet.Hosting.Tests", context.ApplicationName);
            }
        }
Пример #6
0
        public void EnvDefaultsToDevelopmentIfNoConfig()
        {
            var context = new HostingContext
            {
                ServerFactory = this
            };

            var engine = new HostingEngine();

            using (engine.Start(context))
            {
                Assert.Equal("Development", context.EnvironmentName);
                var env = context.ApplicationServices.GetRequiredService<IHostingEnvironment>();
                Assert.Equal("Development", env.EnvironmentName);
            }
        }
Пример #7
0
        public void Main(string[] args)
        {
            var config = new Configuration();
            if (File.Exists(HostingIniFile))
            {
                config.AddIniFile(HostingIniFile);
            }
            config.AddEnvironmentVariables();
            config.AddCommandLine(args);

            var context = new HostingContext()
            {
                Configuration = config,
                ServerFactoryLocation = config.Get("server"),
                ApplicationName = config.Get("app")
            };

            var engine = new HostingEngine(_serviceProvider);

            var serverShutdown = engine.Start(context);
            var loggerFactory = context.ApplicationServices.GetRequiredService<ILoggerFactory>();
            var appShutdownService = context.ApplicationServices.GetRequiredService<IApplicationShutdown>();
            var shutdownHandle = new ManualResetEvent(false);

            appShutdownService.ShutdownRequested.Register(() =>
            {
                try
                {
                    serverShutdown.Dispose();
                }
                catch (Exception ex)
                {
                    var logger = loggerFactory.CreateLogger<Program>();
                    logger.LogError("Dispose threw an exception.", ex);
                }
                shutdownHandle.Set();
            });

            var ignored = Task.Run(() =>
            {
                Console.WriteLine("Started");
                Console.ReadLine();
                appShutdownService.RequestShutdown();
            });

            shutdownHandle.WaitOne();
        }
        public static IServiceProvider CreateServiceProvider(Action<IServiceCollection> configure)
        {
            var context = new HostingContext
            {
                ServerFactory = new ServerFactory(),
                StartupMethods = new StartupMethods(
                    _ => { },
                    services =>
                    {
                        services.AddSignalR();
                        configure(services);
                        return services.BuildServiceProvider();
                    })
            };

            var engine = new HostingEngine().Start(context);
            return context.ApplicationServices;
        }
Пример #9
0
        private static DbContext TryCreateContextFromStartup(Type type)
        {
#if DNX451 || DNXCORE50
            try
            {
                var context = new HostingContext
                {
                    ServerFactory = new ServerFactory(),
                };
                var instance = new HostingEngine().Start(context);
                return context.ApplicationServices.GetService(type) as DbContext;
            }
            catch
            {
            }
#endif

            return null;
        }
Пример #10
0
        public IDisposable Start(HostingContext context)
        {
            EnsureBuilder(context);
            EnsureServerFactory(context);
            InitalizeServerFactory(context);
            EnsureApplicationDelegate(context);

            var applicationLifetime = (ApplicationLifetime)context.Services.GetRequiredService <IApplicationLifetime>();
            var pipeline            = new PipelineInstance(_httpContextFactory, context.ApplicationDelegate);
            var server = context.ServerFactory.Start(context.Server, pipeline.Invoke);

            return(new Disposable(() =>
            {
                applicationLifetime.SignalStopping();
                server.Dispose();
                pipeline.Dispose();
                applicationLifetime.SignalStopped();
            }));
        }
Пример #11
0
        public static IDisposable Start()
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.Add(HostingServices.GetDefaultServices());

            var context = new HostingContext
            {
                Services = serviceCollection.BuildServiceProvider()
            };

            var engine = context.Services.GetService <IHostingEngine>();

            if (engine == null)
            {
                throw new Exception("TODO: IHostingEngine service not available exception");
            }

            return(engine.Start(context));
        }
Пример #12
0
        public Task<int> Main(string[] args)
        {
            //Add command line configuration source to read command line parameters.
            var config = new Configuration();
            config.AddCommandLine(args);

            var context = new HostingContext()
            {
                Configuration = config,
                ServerFactoryLocation = "Microsoft.AspNet.Server.WebListener",
                ApplicationName = "MusicStore"
            };

            using (new HostingEngine().Start(context))
            {
                Console.WriteLine("Started the server..");
                Console.WriteLine("Press any key to stop the server");
                Console.ReadLine();
            }
            return Task.FromResult(0);
        }
Пример #13
0
        public void HostingEngineCanBeStarted()
        {
            var services = HostingServices.Create().BuildServiceProvider();

            var engine = services.GetRequiredService <IHostingEngine>();

            var context = new HostingContext
            {
                ServerFactory   = this,
                Services        = services,
                ApplicationName = "Microsoft.AspNet.Hosting.Tests"
            };

            var engineStart = engine.Start(context);

            Assert.NotNull(engineStart);
            Assert.Equal(1, _startInstances.Count);
            Assert.Equal(0, _startInstances[0].DisposeCalls);

            engineStart.Dispose();

            Assert.Equal(1, _startInstances[0].DisposeCalls);
        }
Пример #14
0
        public void Main(string[] args)
        {
            var applicationRoot = Directory.GetCurrentDirectory();
            var serverPort = 2000;
            var logLevel = LogLevel.Information;
            var hostPID = -1;
            var transportType = TransportType.Http;

            var enumerator = args.GetEnumerator();

            while (enumerator.MoveNext())
            {
                var arg = (string)enumerator.Current;
                if (arg == "-s")
                {
                    enumerator.MoveNext();
                    applicationRoot = Path.GetFullPath((string)enumerator.Current);
                }
                else if (arg == "-p")
                {
                    enumerator.MoveNext();
                    serverPort = int.Parse((string)enumerator.Current);
                }
                else if (arg == "-v")
                {
                    logLevel = LogLevel.Verbose;
                }
                else if (arg == "--hostPID")
                {
                    enumerator.MoveNext();
                    hostPID = int.Parse((string)enumerator.Current);
                }
                else if (arg == "--stdio")
                {
                    transportType = TransportType.Stdio;
                }
            }

            Environment = new OmnisharpEnvironment(applicationRoot, serverPort, hostPID, logLevel, transportType);

            var config = new Configuration()
             .AddCommandLine(new[] { "--server.urls", "http://localhost:" + serverPort });

            var serviceCollection = HostingServices.Create(_serviceProvider, config);
            serviceCollection.AddSingleton<ISharedTextWriter, SharedConsoleWriter>();

            var services = serviceCollection.BuildServiceProvider();
            var hostingEnv = services.GetRequiredService<IHostingEnvironment>();
            var appEnv = services.GetRequiredService<IApplicationEnvironment>();

            var context = new HostingContext()
            {
                Services = services,
                Configuration = config,
                ServerName = "Kestrel",
                ApplicationName = appEnv.ApplicationName,
                EnvironmentName = hostingEnv.EnvironmentName,
            };
            
            if (transportType == TransportType.Stdio)
            {
                context.ServerName = null;
                context.ServerFactory = new Stdio.StdioServerFactory(Console.In, services.GetRequiredService<ISharedTextWriter>());
            }

            var engine = services.GetRequiredService<IHostingEngine>();
            var appShutdownService = services.GetRequiredService<IApplicationShutdown>();
            var shutdownHandle = new ManualResetEvent(false);

            var serverShutdown = engine.Start(context);

            appShutdownService.ShutdownRequested.Register(() =>
            {
                serverShutdown.Dispose();
                shutdownHandle.Set();
            });

#if ASPNETCORE50
            var ignored = Task.Run(() =>
            {
                Console.WriteLine("Started");
                Console.ReadLine();
                appShutdownService.RequestShutdown();
            });
#else
            Console.CancelKeyPress += (sender, e) =>
            {
                appShutdownService.RequestShutdown();
            };
#endif

            if (hostPID != -1)
            {
                try
                {
                    var hostProcess = Process.GetProcessById(hostPID);
                    hostProcess.EnableRaisingEvents = true;
                    hostProcess.OnExit(() => appShutdownService.RequestShutdown());
                }
                catch 
                {
                    // If the process dies before we get here then request shutdown
                    // immediately
                    appShutdownService.RequestShutdown();
                }
            }
            
            shutdownHandle.WaitOne();
        }
Пример #15
0
        public void IsEnvironment_Extension_Is_Case_Insensitive()
        {
            var context = new HostingContext
            {
                ServerFactory = this
            };

            var engine = new HostingEngine();

            using (engine.Start(context))
            {
                var env = context.ApplicationServices.GetRequiredService<IHostingEnvironment>();
                Assert.True(env.IsEnvironment("Development"));
                Assert.True(env.IsEnvironment("developMent"));
            }
        }
Пример #16
0
        private IServiceCollection CreateHostingServices(HostingContext context)
        {
            var services = Import(_fallbackServices);

            services.TryAdd(ServiceDescriptor.Transient<IServerLoader, ServerLoader>());

            services.TryAdd(ServiceDescriptor.Transient<IApplicationBuilderFactory, ApplicationBuilderFactory>());
            services.TryAdd(ServiceDescriptor.Transient<IHttpContextFactory, HttpContextFactory>());

            // TODO: Do we expect this to be provide by the runtime eventually?
            services.AddLogging();
            services.TryAdd(ServiceDescriptor.Singleton<IHttpContextAccessor, HttpContextAccessor>());

            // Apply user services
            services.Add(context.Services);

            // Jamming in app lifetime and hosting env since these must not be replaceable
            services.AddInstance<IApplicationLifetime>(_appLifetime);
            services.AddInstance<IHostingEnvironment>(_hostingEnvironment);

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

            return services;
        }
Пример #17
0
        public void MapPath_Facts(string virtualPath, string expectedSuffix)
        {
            var context = new HostingContext
            {
                ServerFactory = this
            };

            var engine = new HostingEngine();

            using (engine.Start(context))
            {
                var env = context.ApplicationServices.GetRequiredService<IHostingEnvironment>();
                var mappedPath = env.MapPath(virtualPath);
                expectedSuffix = expectedSuffix.Replace('/', Path.DirectorySeparatorChar);
                Assert.Equal(Path.Combine(env.WebRootPath, expectedSuffix), mappedPath);
            }
        }
Пример #18
0
        private void InitalizeServerFactory(HostingContext context)
        {
            if (context.Server == null)
            {
                context.Server = context.ServerFactory.Initialize(context.Configuration);
            }

            if (context.Builder.Server == null)
            {
                context.Builder.Server = context.Server;
            }
        }
Пример #19
0
        private void EnsureStartupMethods(HostingContext context)
        {
            if (context.StartupMethods != null)
            {
                return;
            }

            var diagnosticMessages = new List<string>();
            context.StartupMethods = ApplicationStartup.LoadStartupMethods(
                _fallbackServices,
                context.ApplicationName,
                context.EnvironmentName,
                diagnosticMessages);

            if (context.StartupMethods == null)
            {
                throw new ArgumentException(
                    diagnosticMessages.Aggregate("Failed to find an entry point for the web application.", (a, b) => a + "\r\n" + b),
                    nameof(context));
            }
        }
Пример #20
0
        private void EnsureServerFactory(HostingContext context)
        {
            if (context.ServerFactory != null)
            {
                return;
            }

            if (_serverLoader == null)
            {
                _serverLoader = context.ApplicationServices.GetRequiredService<IServerLoader>();
            }

            context.ServerFactory = _serverLoader.LoadServerFactory(context.ServerFactoryLocation);
        }
Пример #21
0
        private void EnsureContextDefaults(HostingContext context)
        {
            if (context.ApplicationName == null)
            {
                context.ApplicationName = _applicationEnvironment.ApplicationName;
            }

            if (context.EnvironmentName == null)
            {
                context.EnvironmentName = context.Configuration?.Get(EnvironmentKey) ?? HostingEnvironment.DefaultEnvironmentName;
            }

            _hostingEnvironment.EnvironmentName = context.EnvironmentName;

            if (context.WebRootPath != null)
            {
                _hostingEnvironment.WebRootPath = context.WebRootPath;
            }
        }
Пример #22
0
        private void EnsureBuilder(HostingContext context)
        {
            if (context.Builder != null)
            {
                return;
            }

            if (_builderFactory == null)
            {
                _builderFactory = context.ApplicationServices.GetRequiredService<IApplicationBuilderFactory>();
            }

            context.Builder = _builderFactory.CreateBuilder();
            context.Builder.ApplicationServices = context.ApplicationServices;
        }
Пример #23
0
        private void EnsureApplicationServices(HostingContext context)
        {
            if (context.ApplicationServices != null)
            {
                return;
            }

            EnsureStartupMethods(context);

            context.ApplicationServices = context.StartupMethods.ConfigureServicesDelegate(CreateHostingServices(context));
        }
Пример #24
0
        private void EnsureApplicationDelegate(HostingContext context)
        {
            if (context.ApplicationDelegate != null)
            {
                return;
            }

            // REVIEW: should we call EnsureApplicationServices?
            var startupFilters = context.ApplicationServices.GetService<IEnumerable<IStartupFilter>>();
            var configure = context.StartupMethods.ConfigureDelegate;
            foreach (var filter in startupFilters)
            {
                configure = filter.Configure(context.Builder, configure);
            }

            configure(context.Builder);

            context.ApplicationDelegate = context.Builder.Build();
        }
Пример #25
0
        public void WebRootCanBeResolvedFromTheProjectJson()
        {
            var context = new HostingContext
            {
                ServerFactory = this
            };

            var engineStart = new HostingEngine().Start(context);
            var env = context.ApplicationServices.GetRequiredService<IHostingEnvironment>();
            Assert.Equal(Path.GetFullPath("testroot"), env.WebRootPath);
            Assert.True(env.WebRootFileProvider.GetFileInfo("TextFile.txt").Exists);
        }
Пример #26
0
        public void HostingEngineCanBeStarted()
        {
            var context = new HostingContext
            {
                ServerFactory = this,
                ApplicationName = "Microsoft.AspNet.Hosting.Tests"
            };

            var engineStart = new HostingEngine().Start(context);

            Assert.NotNull(engineStart);
            Assert.Equal(1, _startInstances.Count);
            Assert.Equal(0, _startInstances[0].DisposeCalls);

            engineStart.Dispose();

            Assert.Equal(1, _startInstances[0].DisposeCalls);
        }
Пример #27
0
        public void Main(string[] args)
        {
            var config = new Configuration();

            if (File.Exists(HostingIniFile))
            {
                config.AddIniFile(HostingIniFile);
            }
            config.AddEnvironmentVariables();
            config.AddCommandLine(args);

            var appEnv = _serviceProvider.GetRequiredService <IApplicationEnvironment>();

            var hostingEnv = new HostingEnvironment()
            {
                EnvironmentName = config.Get(EnvironmentKey) ?? DefaultEnvironmentName,
                WebRoot         = HostingUtilities.GetWebRoot(appEnv.ApplicationBasePath),
            };

            var serviceCollection = new ServiceCollection();

            serviceCollection.Add(HostingServices.GetDefaultServices(config));
            serviceCollection.AddInstance <IHostingEnvironment>(hostingEnv);
            // The application name is a "good enough" mechanism to identify this application
            // on the machine and to prevent subkeys from being shared across multiple applications
            // by default.
            serviceCollection.Configure <DataProtectionOptions>(options =>
            {
                options.ApplicationDiscriminator = appEnv.ApplicationName;
            });

            var services = serviceCollection.BuildServiceProvider(_serviceProvider);

            var context = new HostingContext()
            {
                Services        = services,
                Configuration   = config,
                ServerName      = config.Get("server"), // TODO: Key names
                ApplicationName = config.Get("app")     // TODO: Key names
                                  ?? appEnv.ApplicationName,
                EnvironmentName = hostingEnv.EnvironmentName,
            };

            var engine             = services.GetRequiredService <IHostingEngine>();
            var appShutdownService = _serviceProvider.GetRequiredService <IApplicationShutdown>();
            var shutdownHandle     = new ManualResetEvent(false);

            var serverShutdown = engine.Start(context);

            appShutdownService.ShutdownRequested.Register(() =>
            {
                serverShutdown.Dispose();
                shutdownHandle.Set();
            });

            var ignored = Task.Run(() =>
            {
                Console.WriteLine("Started");
                Console.ReadLine();
                appShutdownService.RequestShutdown();
            });

            shutdownHandle.WaitOne();
        }