public void RequestServicesAvailableOnlyAfterRequestServices() { var baseServiceProvider = HostingServices.Create().BuildServiceProvider(); var builder = new ApplicationBuilder(baseServiceProvider); bool foundRequestServicesBefore = false; builder.Use(next => async c => { foundRequestServicesBefore = c.RequestServices != null; await next.Invoke(c); }); builder.UseRequestServices(); bool foundRequestServicesAfter = false; builder.Use(next => async c => { foundRequestServicesAfter = c.RequestServices != null; await next.Invoke(c); }); var context = new DefaultHttpContext(); builder.Build().Invoke(context); Assert.False(foundRequestServicesBefore); Assert.True(foundRequestServicesAfter); }
public static TestServer Create(IServiceProvider serviceProvider, Action <IApplicationBuilder> app) { var appServices = HostingServices.Create(serviceProvider).BuildServiceProvider(); var config = new Configuration(); return(new TestServer(config, appServices, app)); }
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 = HostingServices.Create(_hostServiceProvider); var services = serviceCollection.BuildServiceProvider(); var context = new HostingContext() { Services = services, Configuration = config, ServerName = "Microsoft.AspNet.Server.WebListener", ApplicationName = "MusicStore" }; 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)); }
public void CreateWithDelegate() { // Arrange var services = HostingServices.Create().BuildServiceProvider(); // Act & Assert Assert.DoesNotThrow(() => TestServer.Create(services, app => { })); }
public void UseRequestServicesHostingImportedServicesAreDefined(Type service) { var baseServiceProvider = HostingServices.Create().BuildServiceProvider(); var builder = new ApplicationBuilder(baseServiceProvider); builder.UseRequestServices(); Assert.NotNull(builder.ApplicationServices.GetRequiredService(service)); }
public static IServiceProvider CreateServiceProvider(Action <IServiceCollection> configure) { var collection = HostingServices.Create() .AddOptions() .AddDataProtection() .AddSignalR(); configure(collection); return(collection.BuildServiceProvider()); }
public void StartupWithNoConfigureThrows() { var serviceCollection = HostingServices.Create(); serviceCollection.AddInstance <IFakeStartupCallback>(this); var services = serviceCollection.BuildServiceProvider(); var manager = services.GetRequiredService <IStartupManager>(); var ex = Assert.Throws <Exception>(() => manager.LoadStartup("Microsoft.AspNet.Hosting.Tests", "Boom")); Assert.True(ex.Message.Contains("ConfigureBoom or Configure method not found")); }
public static IApplicationBuilder UseServices(this IApplicationBuilder builder, Func <IServiceCollection, IServiceProvider> configureServices) { // Import services from hosting/KRE as fallback var serviceCollection = HostingServices.Create(builder.ApplicationServices); // TODO: remove this once IHttpContextAccessor service is added serviceCollection.AddContextAccessor(); // REVIEW: serviceCollection has the merged services, manifests are lost after this builder.ApplicationServices = configureServices(serviceCollection); return(builder.UseMiddleware <ContainerMiddleware>()); }
public void StartupClassConfigureServicesThatFallsbackToApplicationServices(string env) { var services = HostingServices.Create().BuildServiceProvider(); var manager = services.GetRequiredService <IStartupManager>(); var startup = manager.LoadStartup("Microsoft.AspNet.Hosting.Tests", env); var app = new ApplicationBuilder(services); startup.Invoke(app); Assert.Equal(services, app.ApplicationServices); }
// TODO: KILL THIS private static IServiceProvider BuildFallbackServiceProvider(IEnumerable <IServiceDescriptor> services, IServiceProvider fallback) { var sc = HostingServices.Create(fallback); sc.Add(services); // Build the manifest var manifestTypes = services.Where(t => t.ServiceType.GetTypeInfo().GenericTypeParameters.Length == 0 && t.ServiceType != typeof(IServiceManifest) && t.ServiceType != typeof(IServiceProvider)) .Select(t => t.ServiceType).Distinct(); sc.AddInstance <IServiceManifest>(new ServiceManifest(manifestTypes, fallback.GetRequiredService <IServiceManifest>())); return(sc.BuildServiceProvider()); }
public void StartupClassWithConfigureServicesShouldMakeServiceAvailableInConfigure() { var serviceCollection = HostingServices.Create(); var services = serviceCollection.BuildServiceProvider(); var manager = services.GetRequiredService <IStartupManager>(); var app = new ApplicationBuilder(services); var startup = manager.LoadStartup("Microsoft.AspNet.Hosting.Tests", "WithConfigureServices"); startup.Invoke(app); var foo = app.ApplicationServices.GetRequiredService <StartupWithConfigureServices.IFoo>(); Assert.True(foo.Invoked); }
public void StartupClassAddsConfigureServicesToApplicationServices(string environment) { var services = HostingServices.Create().BuildServiceProvider(); var manager = services.GetRequiredService <IStartupManager>(); var startup = manager.LoadStartup("Microsoft.AspNet.Hosting.Tests", environment ?? ""); var app = new ApplicationBuilder(services); startup.Invoke(app); var options = app.ApplicationServices.GetRequiredService <IOptions <FakeOptions> >().Options; Assert.NotNull(options); Assert.True(options.Configured); Assert.Equal(environment, options.Environment); }
// We need to construct an IApplicationEnvironment with a base path that that matches this // website, in order to find the razor files. This is needed because we don't have a guarantee that // the base path of the current app is this site (ex: functional tests). public static IServiceProvider ReplaceProvider(IServiceProvider provider) { var originalEnvironment = provider.GetService <IApplicationEnvironment>(); var libraryManager = provider.GetService <ILibraryManager>(); var info = libraryManager.GetLibraryInformation("PrecompilationWebSite"); var directory = Path.GetDirectoryName(info.Path); var precompilationApplicationEnvironment = new PrecompilationApplicationEnvironment( originalEnvironment, directory); var collection = HostingServices.Create(provider); collection.AddInstance <IApplicationEnvironment>(precompilationApplicationEnvironment); return(new DelegatingServiceProvider(provider, collection.BuildServiceProvider())); }
public void CreateThrowsWithNoManifest() { // Arrange var fallbackServices = new ServiceCollection(); fallbackServices.AddSingleton <IFakeSingletonService, FakeService>(); var instance = new FakeService(); fallbackServices.AddInstance <IFakeServiceInstance>(instance); fallbackServices.AddTransient <IFakeService, FakeService>(); // Act var exp = Assert.Throws <InvalidOperationException>(() => HostingServices.Create(fallbackServices.BuildServiceProvider())); // Assert Assert.True(exp.Message.Contains("No service for type 'Microsoft.Framework.DependencyInjection.ServiceLookup.IServiceManifest'")); }
public static IServiceProvider CreateServices(string testAppName) { var originalProvider = CallContextServiceLocator.Locator.ServiceProvider; var appEnvironment = originalProvider.GetRequiredService <IApplicationEnvironment>(); //When the tests are run the appEnvironment points to test project. //Change the app environment to point to the test application to be used //by test. var originalAppBase = appEnvironment.ApplicationBasePath; ////Microsoft.Framework.CodeGeneration.Core.FunctionalTest var testAppPath = Path.GetFullPath(Path.Combine(originalAppBase, "..", "TestApps", testAppName)); var services = HostingServices.Create(originalProvider); services.AddInstance( typeof(IApplicationEnvironment), new TestApplicationEnvironment(appEnvironment, testAppPath, testAppName)); return(services.BuildServiceProvider()); }
public void GetHubContextRejectsInvalidTypes() { //var resolver = new DefaultDependencyResolver(); var serviceProvider = HostingServices.Create() .AddOptions() .AddDataProtection() .AddSignalR() .BuildServiceProvider(); var manager = serviceProvider.GetRequiredService <IConnectionManager>(); Assert.Throws <InvalidOperationException>(() => manager.GetHubContext <DemoHub, IDontReturnVoidOrTask>()); Assert.Throws <InvalidOperationException>(() => manager.GetHubContext <DemoHub, IHaveOutParameter>()); Assert.Throws <InvalidOperationException>(() => manager.GetHubContext <DemoHub, IHaveRefParameter>()); Assert.Throws <InvalidOperationException>(() => manager.GetHubContext <DemoHub, IHaveProperties>()); Assert.Throws <InvalidOperationException>(() => manager.GetHubContext <DemoHub, IHaveIndexer>()); Assert.Throws <InvalidOperationException>(() => manager.GetHubContext <DemoHub, IHaveEvent>()); Assert.Throws <InvalidOperationException>(() => manager.GetHubContext <DemoHub, IAmDerivedFromInvalidInterface>()); Assert.Throws <InvalidOperationException>(() => manager.GetHubContext <DemoHub, NotAnInterface>()); }
public void CanHideImportedServices() { // Arrange var fallbackServices = new ServiceCollection(); var fallbackInstance = new FakeService(); fallbackServices.AddInstance <IFakeService>(fallbackInstance); fallbackServices.AddInstance <IServiceManifest>(new ServiceManifest(new Type[] { typeof(IFakeService) })); var services = HostingServices.Create(fallbackServices.BuildServiceProvider()); var realInstance = new FakeService(); services.AddInstance <IFakeService>(realInstance); // Act var provider = services.BuildServiceProvider(); // Assert Assert.Equal(realInstance, provider.GetRequiredService <IFakeService>()); }
public void StartupClassWithConfigureServicesAndUseServicesHidesConfigureServices() { var services = HostingServices.Create().BuildServiceProvider(); var manager = services.GetRequiredService <IStartupManager>(); var startup = manager.LoadStartup("Microsoft.AspNet.Hosting.Tests", "UseServices"); var app = new ApplicationBuilder(services); startup.Invoke(app); Assert.NotNull(app.ApplicationServices.GetRequiredService <FakeService>()); Assert.Null(app.ApplicationServices.GetService <IFakeService>()); var options = app.ApplicationServices.GetRequiredService <IOptions <FakeOptions> >().Options; Assert.NotNull(options); Assert.Equal("Configured", options.Message); Assert.False(options.Configured); // Options never resolved from inner containers }
// When running in memory tests the application base path will point to the functional tests // project folder. // We need to replace it to point to the actual precompilation website so that the views can // be found. public static IServiceProvider ReplaceProvider(IServiceProvider provider) { var originalEnvironment = provider.GetService <IApplicationEnvironment>(); var newPath = Path.GetFullPath( Path.Combine( originalEnvironment.ApplicationBasePath, "..", "WebSites", "PrecompilationWebSite")); var precompilationApplicationEnvironment = new PrecompilationApplicationEnvironment( originalEnvironment, newPath); var collection = HostingServices.Create(provider); collection.AddInstance <IApplicationEnvironment>(precompilationApplicationEnvironment); return(new DelegatingServiceProvider(provider, collection.BuildServiceProvider())); }
public void CreateImportsServices() { // Arrange var fallbackServices = new ServiceCollection(); fallbackServices.AddSingleton <IFakeSingletonService, FakeService>(); var instance = new FakeService(); var factoryInstance = new FakeFactoryService(instance); fallbackServices.AddInstance <IFakeServiceInstance>(instance); fallbackServices.AddTransient <IFakeService, FakeService>(); fallbackServices.AddSingleton <IFactoryService>(serviceProvider => factoryInstance); fallbackServices.AddTransient <IFakeScopedService, FakeService>(); // Don't register in manifest fallbackServices.AddInstance <IServiceManifest>(new ServiceManifest( new Type[] { typeof(IFakeServiceInstance), typeof(IFakeService), typeof(IFakeSingletonService), typeof(IFactoryService), typeof(INonexistentService) })); var services = HostingServices.Create(fallbackServices.BuildServiceProvider()); // Act var provider = services.BuildServiceProvider(); var singleton = provider.GetRequiredService <IFakeSingletonService>(); var transient = provider.GetRequiredService <IFakeService>(); var factory = provider.GetRequiredService <IFactoryService>(); // Assert Assert.Same(singleton, provider.GetRequiredService <IFakeSingletonService>()); Assert.NotSame(transient, provider.GetRequiredService <IFakeService>()); Assert.Same(instance, provider.GetRequiredService <IFakeServiceInstance>()); Assert.Same(factoryInstance, factory); Assert.Same(factory.FakeService, instance); Assert.Null(provider.GetService <INonexistentService>()); Assert.Null(provider.GetService <IFakeScopedService>()); // Make sure we don't leak non manifest services }
private static DbContext TryCreateContextFromStartup(Type type) { #if ASPNET50 || ASPNETCORE50 try { var hostingServiceCollection = HostingServices.Create(); var hostingServices = hostingServiceCollection.BuildServiceProvider(); var assembly = type.GetTypeInfo().Assembly; var startupType = assembly.DefinedTypes.FirstOrDefault(t => t.Name.Equals("Startup", StringComparison.Ordinal)); var instance = ActivatorUtilities.GetServiceOrCreateInstance(hostingServices, startupType.AsType()); var servicesMethod = startupType.GetDeclaredMethod("ConfigureServices"); hostingServiceCollection.AddOptions(); servicesMethod.Invoke(instance, new[] { hostingServiceCollection }); var applicationServices = hostingServiceCollection.BuildServiceProvider(); return(applicationServices.GetService(type) as DbContext); } catch { } #endif return(null); }
public void EnsureRequestServicesSetsRequestServices(bool initializeApplicationServices) { var baseServiceProvider = HostingServices.Create().BuildServiceProvider(); var builder = new ApplicationBuilder(baseServiceProvider); bool foundRequestServicesBefore = false; builder.Use(next => async c => { foundRequestServicesBefore = c.RequestServices != null; await next.Invoke(c); }); builder.Use(next => async c => { using (var container = RequestServicesContainer.EnsureRequestServices(c, baseServiceProvider)) { await next.Invoke(c); } }); bool foundRequestServicesAfter = false; builder.Use(next => async c => { foundRequestServicesAfter = c.RequestServices != null; await next.Invoke(c); }); var context = new DefaultHttpContext(); if (initializeApplicationServices) { context.ApplicationServices = baseServiceProvider; } builder.Build().Invoke(context); Assert.False(foundRequestServicesBefore); Assert.True(foundRequestServicesAfter); }
public void Main(string[] args) { var applicationRoot = Directory.GetCurrentDirectory(); var serverPort = 2000; var logLevel = LogLevel.Information; 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; } } Environment = new OmnisharpEnvironment(applicationRoot, serverPort, logLevel); var config = new Configuration() .AddCommandLine(new[] { "--server.urls", "http://localhost:" + serverPort }); var serviceCollection = HostingServices.Create(_serviceProvider, config); 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, }; var engine = services.GetRequiredService <IHostingEngine>(); var appShutdownService = services.GetRequiredService <IApplicationShutdown>(); var shutdownHandle = new ManualResetEventSlim(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 shutdownHandle.Wait(); }
public TestClientTests() { _services = HostingServices.Create().BuildServiceProvider(); _server = TestServer.Create(_services, app => app.Run(ctx => Task.FromResult(0))); }
public Action <IApplicationBuilder> LoadStartup( string applicationName, string environmentName, IList <string> diagnosticMessages) { if (String.IsNullOrEmpty(applicationName)) { return(_next.LoadStartup(applicationName, environmentName, diagnosticMessages)); } var assembly = Assembly.Load(new AssemblyName(applicationName)); if (assembly == null) { throw new Exception(String.Format("TODO: assembly {0} failed to load message", applicationName)); } var startupName1 = "Startup" + environmentName; var startupName2 = "Startup"; // Check the most likely places first var type = assembly.GetType(startupName1) ?? assembly.GetType(applicationName + "." + startupName1) ?? assembly.GetType(startupName2) ?? assembly.GetType(applicationName + "." + startupName2); if (type == null) { // Full scan var definedTypes = assembly.DefinedTypes.ToList(); var startupType1 = definedTypes.Where(info => info.Name.Equals(startupName1, StringComparison.Ordinal)); var startupType2 = definedTypes.Where(info => info.Name.Equals(startupName2, StringComparison.Ordinal)); var typeInfo = startupType1.Concat(startupType2).FirstOrDefault(); if (typeInfo != null) { type = typeInfo.AsType(); } } if (type == null) { throw new Exception(String.Format("TODO: {0} or {1} class not found in assembly {2}", startupName1, startupName2, applicationName)); } var configureMethod = FindMethod(type, "Configure{0}", environmentName, typeof(void), required: true); var servicesMethod = FindMethod(type, "Configure{0}Services", environmentName, typeof(IServiceProvider), required: false) ?? FindMethod(type, "Configure{0}Services", environmentName, typeof(void), required: false); object instance = null; if (!configureMethod.IsStatic || (servicesMethod != null && !servicesMethod.IsStatic)) { instance = ActivatorUtilities.GetServiceOrCreateInstance(_services, type); } return(builder => { if (servicesMethod != null) { var services = HostingServices.Create(builder.ApplicationServices); // TODO: remove this once IHttpContextAccessor service is added services.AddContextAccessor(); if (servicesMethod.ReturnType == typeof(IServiceProvider)) { // IServiceProvider ConfigureServices(IServiceCollection) builder.ApplicationServices = (Invoke(servicesMethod, instance, builder, services) as IServiceProvider) ?? builder.ApplicationServices; } else { // void ConfigureServices(IServiceCollection) Invoke(servicesMethod, instance, builder, services); if (builder != null) { builder.ApplicationServices = services.BuildServiceProvider(); } } } Invoke(configureMethod, instance, builder); }); }
public void Main(string[] args) { var applicationRoot = Directory.GetCurrentDirectory(); var serverPort = 2000; var logLevel = LogLevel.Information; var hostPID = -1; var transportType = TransportType.Http; var otherArgs = new List <string>(); 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; } else { otherArgs.Add((string)enumerator.Current); } } Environment = new OmnisharpEnvironment(applicationRoot, serverPort, hostPID, logLevel, transportType, otherArgs.ToArray()); 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(); }