Beispiel #1
0
        public override bool OnInit()
        {
            coreConfig = new CoreConfig(startup.Name);

            //Create the log.
            logListener = new LogFileListener();
            logListener.openLogFile(CoreConfig.LogFile);
            Log.Default.addLogListener(logListener);
            Log.ImportantInfo("Running from directory {0}", FolderFinder.ExecutableFolder);
            startup.ConfigureServices(services);
            BuildPluginManager();

            //Create containers
            var scope = this.pluginManager.GlobalScope;

            //Build engine
            var pluginManager = scope.ServiceProvider.GetRequiredService <PluginManager>();

            mainTimer = scope.ServiceProvider.GetRequiredService <UpdateTimer>();
            var frameClearManager = scope.ServiceProvider.GetRequiredService <FrameClearManager>();

            PerformanceMonitor.setupEnabledState(scope.ServiceProvider.GetRequiredService <SystemTimer>());

            MyGUIInterface.Instance.CommonResourceGroup.addResource(GetType().AssemblyQualifiedName, "EmbeddedScalableResource", true);
            MyGUIInterface.Instance.CommonResourceGroup.addResource(startup.GetType().AssemblyQualifiedName, "EmbeddedScalableResource", true);

            startup.Initialized(this, pluginManager);

            if (Initialized != null)
            {
                Initialized.Invoke(this);
            }

            return(true);
        }
Beispiel #2
0
        public IGameBuilder UseStartup <TStartup>() where TStartup : class, IStartup, new()
        {
            _startup = new TStartup();
            _startup.ConfigureServices(_serviceCollection);

            return(this);
        }
Beispiel #3
0
        public static void Start(IStartup application)
        {
            Application.Current.Use(new HtmlFromJsonProvider());
            Application.Current.Use(new PartialToStandaloneHtmlProvider(
                                        File.ReadAllText(Path.Combine(Application.Current.WorkingDirectory, @"wwwroot\BootstrapExample\views\AppShell.html"))));

            var services = new ServiceCollection();

            AddDefaultServices(services);
            application.ConfigureServices(services);

            var serviceProvider = services.BuildServiceProvider();
            var logger          = serviceProvider.GetRequiredService <ILogger <DefaultStarcounterBootstrapper> >();

            logger.LogInformation($"Configuring application {application}");
            var applicationBuilder = new ApplicationBuilder()
            {
                ApplicationServices = serviceProvider
            };
            Action <IApplicationBuilder> configure = application.Configure;

            foreach (var startupFilter in serviceProvider.GetServices <IStartupFilter>().Reverse())
            {
                configure = startupFilter.Configure(configure);
            }

            configure(applicationBuilder);
            logger.LogInformation($"Started application {application}");
        }
        public IHost Build()
        {
            foreach (var keyValuePair in Properties.Select(x => new KeyValuePair <object, object>(x.Key, x.Value)))
            {
                _frontSideBuilder.Properties.Add(keyValuePair);
                _backSideBuilder.Properties.Add(keyValuePair);
            }

            _startup = _backSideBuilder
                       .Build()
                       .Services
                       .GetService <IStartup>();

            if (_startup != null)
            {
                _frontSideBuilder
                .ConfigureServices(services => _startup.ConfigureServices(services));

                _frontSideBuilder
                .ConfigureHostConfiguration(builder => _startup.Configure(_frontSideBuilder));
            }

            return
                (_frontSideBuilder
                 .Build());
        }
        public static void AddEmbedded(
            this IApplicationBuilder appBuilder,
            PathString path,
            string startupTypeName,
            Func <HttpMessageHandler> messageHandlerFactory = null)
        {
            IConfiguration config = appBuilder.ApplicationServices
                                    .GetRequiredService <IConfiguration>();

            IHostingEnvironment environment = appBuilder.ApplicationServices
                                              .GetRequiredService <IHostingEnvironment>();

            ILoggerFactory loggerFactory = appBuilder.ApplicationServices
                                           .GetRequiredService <ILoggerFactory>();

            IStartup startup = CreateStartupInstance(
                startupTypeName,
                config,
                environment,
                loggerFactory,
                messageHandlerFactory);

            appBuilder.MapStartup(
                path,
                environment,
                config,
                (services) =>
            {
                startup.ConfigureServices(services);
            },
                (app) =>
            {
                startup.Configure(app);
            });
        }
Beispiel #6
0
        public void Configure()
        {
            var env = new HostingEnvironment();

            var services = new ServiceCollection();

            services.AddSingleton <IHostingEnvironment, HostingEnvironment>();
            services.AddSingleton <IApplicationLifetime, ApplicationLifetime>();
            services.AddSingleton <IApplicationBuilder, ApplicationBuilder>();
            services.AddLogging();

            IStartup startup = FindAndConstructStartupViaReflection(env);

            startup.ConfigureServices(services);

            _serviceProvider = services.BuildServiceProvider();

            _logger = _serviceProvider.GetRequiredService <ILogger <ConsoleHost> >();

            _applicationBuilder  = _serviceProvider.GetRequiredService <IApplicationBuilder>();
            _applicationLifetime = _serviceProvider.GetRequiredService <IApplicationLifetime>() as ApplicationLifetime;
            var loggerFactory = _serviceProvider.GetRequiredService <ILoggerFactory>();

            startup.Configure(_applicationBuilder, env, loggerFactory, _applicationLifetime);
        }
Beispiel #7
0
 void EnsureApplicationServices()
 {
     if (Services == null)
     {
         EnsureStartup();
         Services = _startup.ConfigureServices(_applicationServiceCollection);
     }
 }
Beispiel #8
0
 private void EnsureApplicationServices()
 {
     if (_applicationServices == null)
     {
         EnsureStartup();
         _applicationServices = _startup.ConfigureServices(_builder);
     }
 }
Beispiel #9
0
 private void EnsureApplicationServices()
 {
     if (_applicationServices == null)
     {
         EnsureStartup();
         _applicationServices = _startup.ConfigureServices(this._applicationServiceCollection);
     }
 }
        public SWContainerBuilder UseStartUp <T>()
            where T : IStartup, new()
        {
            startup = new T() as IStartup;

            startup.ConfigureServices(this);

            this.RegisterInstance(startup).As <IStartup>();

            return(this);
        }
        public IServiceProvider CreateServiceProvider(IServiceCollection services)
        {
            _startup.ConfigureServices(services);

            var typedStartup = _startup.GetType()
                               .GetInterfaces()
                               .SingleOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IStartup <>));

            var containerType = typedStartup?.GetGenericArguments().Single() ?? typeof(IServiceCollection);

            return((IServiceProvider)GetType()
                   .GetMethod(nameof(CreateServiceProvider), BindingFlags.Instance | BindingFlags.NonPublic)
                   .MakeGenericMethod(containerType)
                   .Invoke(this, new object[] { _startup, services }));
        }
        /// <summary>
        /// Uses the given instance as the start up class for the edge module.
        /// </summary>
        /// <param name="hostBuilder">The host builder.</param>
        /// <param name="startup">The instance of the start up class.</param>
        /// <returns>The host builder.</returns>
        internal static IHostBuilder UseStartup(this IHostBuilder hostBuilder, IStartup startup)
        {
            _ = startup ?? throw new ArgumentNullException(nameof(startup));

            return(hostBuilder.ConfigureServices(serviceCollection =>
            {
                startup.ConfigureServices(serviceCollection);

                serviceCollection.AddSingleton(_ => startup);

                if (!serviceCollection.Any(p => p.ServiceType == typeof(IModuleClient)))
                {
                    serviceCollection.AddSingleton(CreateModuleClient);
                }
            }));
        }
        public static IWebHostBuilder UseStartup(this IWebHostBuilder builder, Type startupType)
        {
            var typeInfo     = startupType.GetTypeInfo();
            var constructors = typeInfo.GetConstructors()
                               .Where(x => x.IsPublic)
                               .OrderBy(x => x.GetParameters().Length);

            IStartup startup = null;

            foreach (var constructor in constructors)
            {
                var parameters = constructor.GetParameters();
                var objParams  = new object[parameters.Length];
                int i          = 0;
                for (i = 0; i < parameters.Length; i++)
                {
                    if (DefaultParamterValue.TryGetDefaultValue(parameters[i], out var value))
                    {
                        objParams[i] = value;
                        var x = new ConfigurationBuilder();
                    }
                    else
                    {
                        break;
                    }
                }

                if (i < parameters.Length)
                {
                    continue;
                }

                startup = (IStartup)constructor.Invoke(objParams);
                break;
            }

            if (startup == null)
            {
                throw new InvalidOperationException("操作失败,无法构造出Startup类");
            }

            return(builder.Configure(
                       services => startup.ConfigureServices(services),
                       app => startup.Configure(app)));
        }
Beispiel #14
0
        public RequestDelegate BuildApplication()
        {
            _startup             = _hostingServiceProvider.GetRequiredService <IStartup>();
            _applicationServices = _startup.ConfigureServices(_applicationServiceCollection);

            var builder = new OicApplicationBuilder(_applicationServices);

            var startupFilters = _applicationServices.GetService <IEnumerable <IStartupFilter> >();
            Action <IApplicationBuilder> configure = _startup.Configure;

            foreach (var filter in startupFilters.Reverse())
            {
                configure = filter.Configure(configure);
            }

            configure(builder);

            return(builder.Build());
        }
Beispiel #15
0
 /// <summary>
 /// Responsible for calling any user-defined startup declared in the running lib
 /// </summary>
 /// <param name="services"></param>
 private static void CallUserDefinedStartup(IServiceCollection services)
 {
     try
     {
         //Call user defined startup:
         var type  = typeof(IStartup);
         var types = AppDomain.CurrentDomain.GetAssemblies()
                     .SelectMany(s => s.GetTypes())
                     .Where(p => type.IsAssignableFrom(p) && !p.IsInterface && !p.IsAbstract);
         foreach (var t in types)
         {
             IStartup instance = (IStartup)Activator.CreateInstance(t) !;
             instance.ConfigureServices(services);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine($"Could not call user-defined IStartup: {e}");
     }
 }
Beispiel #16
0
        protected static void InitPlatform(IStartup startup = null, Action <IServiceCollection> platformBuild = null)
        {
            var services = new ServiceCollection();

            // add standard infrastructure
            services.AddSingleton <IMessageBus, MessageBus>();

            startup?.ConfigureServices(services);
            platformBuild?.Invoke(services);
            Services = services;

            container = startup?.CreateServiceProvider(services) ?? services.BuildServiceProvider();
            startup?.ConfigureApp(container);

            container.RunPostBuildActions();
            var tasks = container.GetServices <IStartupTask>();

            foreach (var task in tasks)
            {
                task.Start();
            }
        }
 public IServiceProvider ConfigureServices(IServiceCollection services)
 {
     _configureServices(services);
     return(_startupImplementation.ConfigureServices(services));
 }
Beispiel #18
0
 public IServiceProvider ConfigureServices(IServiceCollection services)
 {
     _startup.ConfigureServices(services);
     return(services.BuildServiceProvider());
 }
        /// <summary>
        /// Creates a web server that will bind to local addresses to any available port.
        /// </summary>
        /// <param name="isPrivate">
        /// Whether or not the host should bind to the loopback adapter, or a public interface.
        /// </param>
        /// <param name="isV6">
        /// Whether or not this server should be bound to a v6 address. We have yet to determine if
        /// we can even grab some internal of kestrel that will allow us to manipulate the listener
        /// socket endpoint to force it into dual mode, so we use this option instead and generate
        /// two hosts.
        /// </param>
        /// <param name="boundHttpEndpoint">
        /// The endpoint that the HTTP host was bound to.
        /// </param>
        /// <param name="startupInsance">
        /// The startup instance to use for the server.
        /// </param>
        /// <returns>
        /// An IWebHost that will transparently proxy all requests.
        /// </returns>
        /// <exception cref="NullReferenceException">
        /// In the event that the internal kestrel engine doesn't properly initialize, this method
        /// will throw.
        /// </exception>
        private IWebHost CreateHost <T>(bool isPrivate, bool isV6, out IPEndPoint boundHttpEndpoint, IStartup startupInsance) where T : class
        {
            WebHostBuilder ipWebhostBuilder = new WebHostBuilder();

            ListenOptions httpListenOptions = null;

            ipWebhostBuilder.UseSockets(opts =>
            {
                //opts.IOQueueCount = 0;
                opts.IOQueueCount = byte.MaxValue;
            });

            // Use Kestrel server.
            ipWebhostBuilder.UseKestrel(opts =>
            {
                opts.Limits.MaxRequestBodySize               = null;
                opts.Limits.MaxConcurrentConnections         = null;
                opts.Limits.MaxConcurrentUpgradedConnections = null;
                opts.Limits.MaxRequestLineSize               = ushort.MaxValue;
                opts.Limits.MaxResponseBufferSize            = ushort.MaxValue * byte.MaxValue;
                opts.Limits.MinResponseDataRate              = null; //new MinDataRate(ushort.MaxValue * 10, TimeSpan.FromSeconds(30));
                opts.AddServerHeader           = false;
                opts.ApplicationSchedulingMode = Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.SchedulingMode.Inline;
                opts.AllowSynchronousIO        = true;

                // Listen for HTTPS connections. Keep a reference to the options object so we can get
                // the chosen port number after we call start.
                opts.Listen(isV6 ? IPAddress.IPv6Any : IPAddress.Any, 0, listenOpts =>
                {
                    // Plug in our TLS connection adapter. This adapter will handle SNI parsing and
                    // certificate spoofing based on the SNI value.
                    listenOpts.ConnectionAdapters.Add(_tlsConnAdapter);

                    // Who doesn't love to kick that old Nagle to the curb?
                    listenOpts.NoDelay = true;

                    // HTTP 2 got cut last minute from 2.1 and MS speculates that it may take several
                    // releases to get it properly included.
                    // https://github.com/aspnet/Docs/issues/5242#issuecomment-380863456
                    listenOpts.Protocols = HttpProtocols.Http1AndHttp2;

                    httpListenOptions = listenOpts;
                });
            });

            // Add compression for responses.
            ipWebhostBuilder.ConfigureServices(serviceOpts =>
            {
                startupInsance.ConfigureServices(serviceOpts);
                //serviceOpts.AddResponseCompression();

                // Add existing startup instance! This is how/where we handle connections.
                serviceOpts.AddSingleton <IStartup>(startupInsance);
            });

            ipWebhostBuilder.Configure(cfgApp =>
            {
                startupInsance.Configure(cfgApp);
                //cfgApp.UseResponseCompression();
            });

            // Build host. You needed this comment.
            var vHost = ipWebhostBuilder.Build();

            // Start the host. You definitely needed this. It's not until we start the host that the
            // listener endpoints will be resolved. We need that info so we know where our proxy
            // server is running, so we can divert packets to it.
            vHost.Start();

            // Since this is post vHost.Start(), we can now grab the EP of the connection.
            if (httpListenOptions != null)
            {
                boundHttpEndpoint = httpListenOptions.IPEndPoint;
            }
            else
            {
                throw new NullReferenceException("httpListenOptions is expected to be non-null!");
            }

            return(vHost);
        }