Exemple #1
0
        public static TestServer Create(IServiceProvider provider, Action <IApplicationBuilder> app)
        {
            var appEnv = provider.GetRequiredService <IApplicationEnvironment>();

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

            var collection = new ServiceCollection();

            collection.Add(HostingServices.GetDefaultServices());
            collection.AddInstance <IHostingEnvironment>(hostingEnv);

            var appServices = collection.BuildServiceProvider(provider);

            var config = new Configuration();

            return(new TestServer(config, appServices, app));
        }
Exemple #2
0
        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
        }
Exemple #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));
            serviceCollection.AddInstance <IHostingEnvironment>(new HostingEnvironment()
            {
                WebRoot = "wwwroot"
            });
            var services = serviceCollection.BuildServiceProvider(_hostServiceProvider);

            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));
        }
Exemple #4
0
        public void EnsureRequestServicesSetsRequestServices(bool initializeApplicationServices)
        {
            var baseServiceProvider = new ServiceCollection()
                                      .Add(HostingServices.GetDefaultServices())
                                      .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);
        }
Exemple #5
0
        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);
        }
Exemple #6
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 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();
        }
Exemple #7
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 traceType       = TraceType.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")
                {
                    traceType = TraceType.Verbose;
                }
            }

            var environment = new OmnisharpEnvironment(applicationRoot, serverPort, traceType);
            var hostingEnv  = new HostingEnvironment {
                EnvironmentName = "Development"
            };

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

            var serviceCollection = new ServiceCollection();

            serviceCollection.Add(HostingServices.GetDefaultServices(config));
            serviceCollection.AddInstance <IOmnisharpEnvironment>(environment);
            serviceCollection.AddInstance <IHostingEnvironment>(hostingEnv);

            var services = serviceCollection
                           .BuildServiceProvider(_serviceProvider);

            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 = _serviceProvider.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();
        }
Exemple #9
0
        public TestClientTests()
        {
            _services = HostingServices.Create().BuildServiceProvider();

            _server = TestServer.Create(_services, app => app.Run(ctx => Task.FromResult(0)));
        }