public DnxProjectSystem(OmnisharpWorkspace workspace,
                                    IOmnisharpEnvironment env,
                                    IOptions<OmniSharpOptions> optionsAccessor,
                                    ILoggerFactory loggerFactory,
                                    IMetadataFileReferenceCache metadataFileReferenceCache,
                                    IApplicationLifetime lifetime,
                                    IFileSystemWatcher watcher,
                                    IEventEmitter emitter,
                                    DnxContext context)
        {
            _workspace = workspace;
            _env = env;
            _logger = loggerFactory.CreateLogger<DnxProjectSystem>();
            _metadataFileReferenceCache = metadataFileReferenceCache;
            _options = optionsAccessor.Options;
            _dnxPaths = new DnxPaths(env, _options, loggerFactory);
            _designTimeHostManager = new DesignTimeHostManager(loggerFactory, _dnxPaths);
            _packagesRestoreTool = new PackagesRestoreTool(_options, loggerFactory, emitter, context, _dnxPaths);
            _context = context;
            _watcher = watcher;
            _emitter = emitter;
            _directoryEnumerator = new DirectoryEnumerator(loggerFactory);

            lifetime.ApplicationStopping.Register(OnShutdown);
        }
Exemplo n.º 2
0
        public void Configure(IApplicationBuilder app, IApplicationLifetime lifetime, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.Map("/simplewebapi", (app1) => this.ConfigureIIS(app1, lifetime, env, loggerFactory));

            app.UseMvc();

            app.UseWelcomePage();
        }
 public LocalJsonRepoSetProvider(
     IOptions<LocalJsonRepoSetProviderOptions> localJsonRepoSetProviderOptions,
     IHostingEnvironment hostingEnvironment,
     IApplicationLifetime applicationLifetime,
     ILogger<LocalJsonRepoSetProvider> logger)
     : base(hostingEnvironment, applicationLifetime, logger)
 {
     PhysicalJsonFilePath = Path.Combine(hostingEnvironment.ContentRootPath, localJsonRepoSetProviderOptions.Value.JsonFilePath);
 }
 public RemoteJsonRepoSetProvider(
     IOptions<RemoteJsonRepoSetProviderOptions> remoteJsonRepoSetProviderOptions,
     IHostingEnvironment hostingEnvironment,
     IApplicationLifetime applicationLifetime,
     ILogger<RemoteJsonRepoSetProvider> logger)
     : base(hostingEnvironment, applicationLifetime, logger)
 {
     RemoteJsonFileUrl = remoteJsonRepoSetProviderOptions.Value.JsonFileUrl;
 }
 public JsonRepoSetProvider(
     IHostingEnvironment hostingEnvironment,
     IApplicationLifetime applicationLifetime,
     ILogger<JsonRepoSetProvider> logger)
 {
     HostingEnvironment = hostingEnvironment;
     ApplicationLifetime = applicationLifetime;
     Logger = logger;
 }
Exemplo n.º 6
0
 public WebSocketTransport(HttpContext context,
                           JsonSerializer serializer,
                           ITransportHeartbeat heartbeat,
                           IPerformanceCounterManager performanceCounterManager,
                           IApplicationLifetime applicationLifetime,
                           ILoggerFactory loggerFactory,
                           IMemoryPool pool)
     : this(context, serializer, heartbeat, performanceCounterManager, applicationLifetime, loggerFactory, pool, maxIncomingMessageSize: null)
 {
 }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc();

            applicationLifetime.ApplicationStarted.Register(HandleStarted);
            applicationLifetime.ApplicationStopped.Register(HandleStopped);
        }
 public ServerSentEventsTransport(HttpContext context,
                                  JsonSerializer jsonSerializer,
                                  ITransportHeartbeat heartbeat,
                                  IPerformanceCounterManager performanceCounterManager,
                                  IApplicationLifetime applicationLifetime,
                                  ILoggerFactory loggerFactory,
                                  IMemoryPool pool)
     : base(context, jsonSerializer, heartbeat, performanceCounterManager, applicationLifetime, loggerFactory, pool)
 {
     _counters = performanceCounterManager;
 }
Exemplo n.º 9
0
 public KestrelThread(KestrelEngine engine)
 {
     _engine = engine;
     _appLifetime = engine.AppLifetime;
     _log = engine.Log;
     _threadPool = engine.ThreadPool;
     _loop = new UvLoopHandle(_log);
     _post = new UvAsyncHandle(_log);
     _thread = new Thread(ThreadStart);
     _thread.Name = "KestrelThread - libuv";
     QueueCloseHandle = PostCloseHandle;
 }
Exemplo n.º 10
0
 protected ForeverTransport(HttpContext context,
                            JsonSerializer jsonSerializer,
                            ITransportHeartbeat heartbeat,
                            IPerformanceCounterManager performanceCounterManager,
                            IApplicationLifetime applicationLifetime,
                            ILoggerFactory loggerFactory,
                            IMemoryPool pool)
     : base(context, heartbeat, performanceCounterManager, applicationLifetime, loggerFactory, pool)
 {
     _jsonSerializer = jsonSerializer;
     _counters = performanceCounterManager;
 }
Exemplo n.º 11
0
 public LongPollingTransport(HttpContext context,
                             JsonSerializer jsonSerializer,
                             ITransportHeartbeat heartbeat,
                             IPerformanceCounterManager performanceCounterManager,
                             IApplicationLifetime applicationLifetime,
                             ILoggerFactory loggerFactory,
                             IOptions<SignalROptions> optionsAccessor,
                             IMemoryPool pool)
     : base(context, jsonSerializer, heartbeat, performanceCounterManager, applicationLifetime, loggerFactory, pool)
 {
     _pollDelay = optionsAccessor.Value.Transports.LongPolling.PollDelay;
     _counters = performanceCounterManager;
 }
Exemplo n.º 12
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            appLifetime.ApplicationStopped.Register(() => ApplicationContainer.Dispose());
        }
Exemplo n.º 13
0
        public void ConfigureServices(IServiceCollection services, IApplicationLifetime liftime, ISharedTextWriter writer)
        {
            Workspace = new OmnisharpWorkspace();

            // Working around another bad bug in ASP.NET 5
            // https://github.com/aspnet/Hosting/issues/151
            services.AddInstance(liftime);
            services.AddInstance(writer);

            // This is super hacky by it's the easiest way to flow serivces from the 
            // hosting layer, this needs to be easier
            services.AddInstance<IOmnisharpEnvironment>(Program.Environment);

            services.AddMvc(Configuration);

            services.Configure<MvcOptions>(opt =>
            {
                opt.ApplicationModelConventions.Add(new FromBodyApplicationModelConvention());
                opt.Filters.Add(new UpdateBufferFilter(Workspace));
            });

            // Add the omnisharp workspace to the container
            services.AddInstance(Workspace);

            // Caching
            services.AddSingleton<IMemoryCache, MemoryCache>();
            services.AddSingleton<IMetadataFileReferenceCache, MetadataFileReferenceCache>();

            // Add the project systems
            services.AddInstance(new AspNet5Context());
            services.AddInstance(new MSBuildContext());

            services.AddSingleton<IProjectSystem, AspNet5ProjectSystem>();
            services.AddSingleton<IProjectSystem, MSBuildProjectSystem>();

            // Add the file watcher
            services.AddSingleton<IFileSystemWatcher, FileSystemWatcherWrapper>();

            // Add test command providers
            services.AddSingleton<ITestCommandProvider, AspNet5TestCommandProvider>();

            // Add the code action provider
            services.AddSingleton<ICodeActionProvider, EmptyCodeActionProvider>();
            
#if ASPNET50
            services.AddSingleton<ICodeActionProvider, NRefactoryCodeActionProvider>();
#endif

            // Setup the options from configuration
            services.Configure<OmniSharpOptions>(Configuration);
        }
Exemplo n.º 14
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");

                // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
                //try
                //{
                //    using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                //        .CreateScope())
                //    {
                //        serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
                //             .Database.Migrate();
                //    }
                //}
                //catch { }
            }


            app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

            app.UseStaticFiles();
            app.UseSession();
            app.UseIdentity();

            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "areaRoute",
                    template: "{area:exists}/{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseUbik(env, loggerFactory, lifetime, Configuration);

        }
Exemplo n.º 15
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime)
        {
            if (app == null) throw new ArgumentNullException(nameof(app));
            if (env == null) throw new ArgumentNullException(nameof(env));
            if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory));

            ConfigureLogging(loggerFactory);

            if (_configuration.GeneralConfigured())
            {
                app.InitalizeDatabase()
                    .InitalizeBus(_configuration, lifetime);
            }

            ConfigureWebApp(app, env);
        }
Exemplo n.º 16
0
 public BackgroundTaskService(
     IOrchardHost orchardHost,
     ShellSettings shellSettings,
     IApplicationLifetime applicationLifetime,
     IEnumerable<IBackgroundTask> tasks,
     ILogger<BackgroundTaskService> logger)
 {
     _shellSettings = shellSettings;
     _orchardHost = orchardHost;
     _applicationLifetime = applicationLifetime;
     _tasks = tasks.GroupBy(GetGroupName).ToDictionary(x => x.Key, x => x.Select(i => i));
     _states = tasks.ToDictionary(x => x, x => BackgroundTaskState.Stopped);
     _timers = _tasks.Keys.ToDictionary(x => x, x => new Timer(DoWork, x, Timeout.Infinite, Timeout.Infinite));
     _periods = _tasks.Keys.ToDictionary(x => x, x => TimeSpan.FromMinutes(1));
     Logger = logger;
 }
Exemplo n.º 17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)
        {
            logger = loggerFactory;
            applicationLifetime.ApplicationStopping.Register(OnShutdown);
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");

                // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
                try
                {
                    using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                        .CreateScope())
                    {
                        serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
                             .Database.Migrate();
                    }
                }
                catch { }
            }

            app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

            app.UseStaticFiles();

            app.UseIdentity();

            // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemplo n.º 18
0
        public void Configure(IApplicationBuilder app, IApplicationLifetime lifetime, ILoggerFactory loggerFactory)
        {
            var webListenerInfo = app.ServerFeatures.Get<WebListener>();
            if (webListenerInfo != null)
            {
                webListenerInfo.AuthenticationManager.AuthenticationSchemes =
                    AuthenticationSchemes.AllowAnonymous;
            }

            var serverAddress = app.ServerFeatures.Get<IServerAddressesFeature>()?.Addresses.FirstOrDefault();

            app.Run(async (context) =>
            {
                var message = String.Format("Hello World from {0}",
                                        serverAddress);
                await context.Response.WriteAsync(message);
            });
        }
Exemplo n.º 19
0
        public WebSocketTransport(HttpContext context,
                                  JsonSerializer serializer,
                                  ITransportHeartbeat heartbeat,
                                  IPerformanceCounterManager performanceCounterManager,
                                  IApplicationLifetime applicationLifetime,
                                  ILoggerFactory loggerFactory,
                                  IMemoryPool pool,
                                  int? maxIncomingMessageSize)
            : base(context, serializer, heartbeat, performanceCounterManager, applicationLifetime, loggerFactory, pool)
        {
            _context = context;
            _maxIncomingMessageSize = maxIncomingMessageSize;

            _message = OnMessage;
            _closed = OnClosed;
            _error = OnSocketError;

            _counters = performanceCounterManager;
        }
Exemplo n.º 20
0
        public AspNet5ProjectSystem(OmnisharpWorkspace workspace,
                                    IOmnisharpEnvironment env,
                                    IOptions<OmniSharpOptions> optionsAccessor,
                                    ILoggerFactory loggerFactory,
                                    IMetadataFileReferenceCache metadataFileReferenceCache,
                                    IApplicationLifetime lifetime,
                                    IFileSystemWatcher watcher,
                                    AspNet5Context context)
        {
            _workspace = workspace;
            _env = env;
            _options = optionsAccessor.Options;
            _logger = loggerFactory.Create<AspNet5ProjectSystem>();
            _metadataFileReferenceCache = metadataFileReferenceCache;
            _designTimeHostManager = new DesignTimeHostManager(loggerFactory);
            _context = context;
            _watcher = watcher;

            lifetime.ApplicationStopping.Register(OnShutdown);
        }
Exemplo n.º 21
0
 public RecipeExecutor(
     IEventBus eventBus,
     ISession session,
     IRecipeParser recipeParser,
     IOrchardFileSystem fileSystem,
     IApplicationLifetime applicationLifetime,
     ShellSettings shellSettings,
     IOrchardHost orchardHost,
     ILogger<RecipeExecutor> logger,
     IStringLocalizer<RecipeExecutor> localizer)
 {
     _orchardHost = orchardHost;
     _shellSettings = shellSettings;
     _applicationLifetime = applicationLifetime;
     _eventBus = eventBus;
     _session = session;
     _recipeParser = recipeParser;
     _fileSystem = fileSystem;
     _logger = logger;
     T = localizer;
 }
Exemplo n.º 22
0
        public DnxProjectSystem(OmnisharpWorkspace workspace,
                                IOmnisharpEnvironment env,
                                ILoggerFactory loggerFactory,
                                IMetadataFileReferenceCache metadataFileReferenceCache,
                                IApplicationLifetime lifetime,
                                IFileSystemWatcher watcher,
                                IEventEmitter emitter,
                                DnxContext context)
        {
            _workspace = workspace;
            _env = env;
            _loggerFactory = loggerFactory;
            _logger = loggerFactory.CreateLogger<DnxProjectSystem>();
            _metadataFileReferenceCache = metadataFileReferenceCache;
            _context = context;
            _watcher = watcher;
            _emitter = emitter;
            _directoryEnumerator = new DirectoryEnumerator(loggerFactory);

            lifetime?.ApplicationStopping.Register(OnShutdown);
        }
 public TreePublishHandler(IRequiredPublishFieldsResolver requiredPublishFieldsResolver, 
     IPublisherOperationService publisherOpsService, 
     IDataStoreFactory dataStoreFactory, 
     IRepositoryFactory<IMediaRepository> mediaRepositoryFactory, 
     IRepositoryFactory<IItemIndexRepository> targetIndexRepositoryFactory, 
     IRepositoryFactory<IItemRepository> itemRepositoryFactory, 
     IRepositoryFactory<IItemRelationshipRepository> itemRelationshipRepoFactory, 
     IRepositoryFactory<IItemNodeRepository> itemNodeRepositoryFactory, 
     IRepositoryFactory<ITemplateGraphRepository> templateGraphRepositoryFactory, 
     IRepositoryFactory<IIndexableItemRepository> indexablePublishTargetRepositoryFactory, 
     IRepositoryFactory<IWorkflowStateRepository> workflowRepositoryFactory, 
     IRepositoryFactory<ITestableContentRepository> testableContentRepositoryFactory, 
     IRepositoryFactory<IManifestRepository> manifestRepositoryFactory,
     IRepositoryFactory<IPublishExclusionsRepository> publishExclusionsRepositoryFactory,
     IPromotionCoordinator promoterCoordinator, 
     IEventRegistry eventRegistry, 
     ILoggerFactory loggerFactory, 
     IApplicationLifetime applicationLifetime, 
     IConfiguration config)
     : this(requiredPublishFieldsResolver, publisherOpsService, dataStoreFactory, mediaRepositoryFactory, targetIndexRepositoryFactory, itemRepositoryFactory, itemRelationshipRepoFactory, itemNodeRepositoryFactory, templateGraphRepositoryFactory, indexablePublishTargetRepositoryFactory, workflowRepositoryFactory, testableContentRepositoryFactory, manifestRepositoryFactory, publishExclusionsRepositoryFactory, promoterCoordinator, eventRegistry, loggerFactory, applicationLifetime, SitecoreConfigurationExtensions.As<PublishJobHandlerOptions>(config))
 {
 }
 /// <summary>
 /// Creates a new instance of Incremental Publish Handler
 /// </summary>
 public IncrementalPublishHandler(IRequiredPublishFieldsResolver requiredPublishFieldsResolver,
     IPublisherOperationService publisherOpsService,
     IDataStoreFactory dataStoreFactory,
     IRepositoryFactory<IMediaRepository> mediaRepositoryFactory,
     IRepositoryFactory<IItemIndexRepository> targetIndexRepositoryFactory,
     IRepositoryFactory<IItemRepository> itemRepositoryFactory,
     IRepositoryFactory<IItemRelationshipRepository> itemRelationshipRepoFactory,
     IRepositoryFactory<IItemNodeRepository> itemNodeRepositoryFactory,
     IRepositoryFactory<ITemplateGraphRepository> templateGraphRepositoryFactory,
     IRepositoryFactory<IIndexableItemRepository> indexablePublishTargetRepositoryFactory,
     IRepositoryFactory<IWorkflowStateRepository> workflowRepositoryFactory,
     IRepositoryFactory<ITestableContentRepository> testableContentRepositoryFactory,
     IRepositoryFactory<IManifestRepository> manifestRepositoryFactory,
     IRepositoryFactory<IPublishExclusionsRepository> publishExclusionsRepositoryFactory,
     IPromotionCoordinator promoterCoordinator,
     IEventRegistry eventRegistry,
     ILoggerFactory loggerFactory,
     IApplicationLifetime applicationLifetime,
     PublishJobHandlerOptions options = null)
     : base(requiredPublishFieldsResolver, publisherOpsService, dataStoreFactory, mediaRepositoryFactory, targetIndexRepositoryFactory, itemRepositoryFactory, itemRelationshipRepoFactory, itemNodeRepositoryFactory, templateGraphRepositoryFactory, indexablePublishTargetRepositoryFactory, workflowRepositoryFactory, testableContentRepositoryFactory, manifestRepositoryFactory, publishExclusionsRepositoryFactory, promoterCoordinator, eventRegistry, loggerFactory, applicationLifetime, options ?? new PublishJobHandlerOptions())
 {
 }
        protected TransportDisconnectBase(HttpContext context, ITransportHeartbeat heartbeat, IPerformanceCounterManager performanceCounterManager, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory, IMemoryPool pool)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (heartbeat == null)
            {
                throw new ArgumentNullException("heartbeat");
            }

            if (performanceCounterManager == null)
            {
                throw new ArgumentNullException("performanceCounterManager");
            }

            if (applicationLifetime == null)
            {
                throw new ArgumentNullException("applicationLifetime");
            }

            if (loggerFactory == null)
            {
                throw new ArgumentNullException("loggerFactory");
            }

            Pool = pool;

            _context = context;
            _heartbeat = heartbeat;
            _counters = performanceCounterManager;
            _hostShutdownToken = applicationLifetime.ApplicationStopping;
            _requestAborted = context.RequestAborted;

            // Queue to protect against overlapping writes to the underlying response stream
            WriteQueue = new TaskQueue();
            _logger = loggerFactory.CreateLogger(GetType().FullName);
        }
Exemplo n.º 26
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
            IApplicationLifetime appLifetime)
        {
            var angularRoutes = new[]
            {
                "/home",
                "/project",
                "/about",
                "/login"
            };

            app.Use(async (context, next) =>
            {
                if (context.Request.Path.HasValue && null != angularRoutes.FirstOrDefault(
                    ar => context.Request.Path.Value.StartsWith(ar, StringComparison.OrdinalIgnoreCase)))
                {
                    context.Request.Path = new PathString("/");
                }

                await next();
            });

            app.UseDefaultFiles();

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    "jsonRoute",
                    "api/{controller}/{action}.json",
                    new {controller = "Home", action = "Index"});
                routes.MapRoute(
                    "viewRoute",
                    "view/{controller}/{action}.html",
                    new {controller = "Home", action = "Index"});
            });
        }
Exemplo n.º 27
0
 public RecipeExecutor(
     IEventBus eventBus,
     ISession session,
     IEnumerable<IRecipeParser> recipeParsers,
     IOptions<RecipeHarvestingOptions> recipeOptions,
     IOrchardFileSystem fileSystem,
     IApplicationLifetime applicationLifetime,
     ShellSettings shellSettings,
     IOrchardHost orchardHost,
     ILogger<RecipeExecutor> logger,
     IStringLocalizer<RecipeExecutor> localizer)
 {
     _orchardHost = orchardHost;
     _shellSettings = shellSettings;
     _applicationLifetime = applicationLifetime;
     _eventBus = eventBus;
     _session = session;
     _recipeParsers = recipeParsers;
     _recipeOptions = recipeOptions.Value;
     _fileSystem = fileSystem;
     _logger = logger;
     T = localizer;
 }
Exemplo n.º 28
0
        public static IApplicationBuilder InitalizeBus(this IApplicationBuilder app, IConfiguration configuration, IApplicationLifetime lifetime)
        {
            if (app == null) throw new ArgumentNullException(nameof(app));
            if (lifetime == null) throw new ArgumentNullException(nameof(lifetime));

            var busControl = BusFactory.CreateBus(configuration, busConfigurator => 
            {
                busConfigurator.ReceiveEndpoint("Soloco.RealTimeWeb", endpointConfiguration =>
                {
                    endpointConfiguration.Consumer(() => new VehicleMonitoConsumer());
                });
            });

            if (busControl != null)
            {
                var busHandle = busControl.Start();

                //todo: handler the bus lifetime by the container
                lifetime.ApplicationStopping.Register(() => { busHandle.Dispose(); });
            }

            return app;
        }
        public DnxProjectSystem CreateProjectSystem(
			Solution solution,
			IApplicationLifetime appLifetime,
			DnxContext context)
        {
            var workspace = new OmnisharpWorkspace ();
            var env = new OmnisharpEnvironment (solution.BaseDirectory);
            var options = new OmniSharpOptionsWrapper ();
            var loggerFactory = new LoggerFactory ();
            var cache = new MetadataFileReferenceCache ();
            var emitter = new EventEmitter ();
            var watcher = new FileSystemWatcherWrapper (env);

            return new DnxProjectSystem (
                workspace,
                env,
                options,
                loggerFactory,
                cache,
                appLifetime,
                watcher,
                emitter,
                context);
        }
Exemplo n.º 30
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory, IApplicationLifetime lifetime, IBusManager busManager)
        {
            loggerfactory.AddSerilog();

            Log.Information("Configuring the Application");

            app.UseCors(_aureliaAppPolicyName);

            var options = new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = _appSettings.IdentityServerAuthority,
                RequiredScopes = new[] { _appSettings.IdentityServerSettings.ClientId },
                NameClaimType = "preferred_username"
            };

            app.UseAppBuilder(
                builder =>
                {
                    builder.SetLoggerFactory(LoggerFactory.Default);
                    builder.UseIdentityServerBearerTokenAuthentication(options);
                },
                _appSettings.ServiceSettings.ServiceName);

            app.UseMiddleware<ContextMiddleware>();
            app.UseMvc();

            Log.Information("Getting ready to start the bus manager");

            busManager.Start(
                new[] { typeof(StartApplication).Assembly, Assembly.GetExecutingAssembly() },
                config => config.RegisterComponents(r => r.ConfigureComponent<OutgoingAppContextMutator>(DependencyLifecycle.InstancePerUnitOfWork)));

            lifetime.ApplicationStopping.Register(busManager.Stop);

            _loggingLevelSwitch.MinimumLevel = LogEventLevel.Information;
        }
Exemplo n.º 31
0
 public RabbitEFService(IConfiguration configuration, ILogger <RabbitEFService> logger, IApplicationLifetime applifetime, EventSinkContext context)
 {
     rabbitConfig = new RabbitConfig();
     configuration.Bind("RabbitMQ", rabbitConfig);
     lifetime    = applifetime;
     this.logger = logger;
     ctx         = context;
 }
Exemplo n.º 32
0
        /// <summary>
        /// Configures the specified application.
        /// </summary>
        /// <param name="app">The application.</param>
        /// <param name="env">The env.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        /// <param name="appLifeTime">The application life time.</param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifeTime)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "ScaffoldCore");
                c.InjectStylesheet("/swagger-ui/theme.css");
                c.DocExpansion(DocExpansion.None);
            });

            app.UseMiddleware <SampleMiddleware>();
            app.UseMvc();
            app.UseStaticFiles();

            appLifeTime.ApplicationStopped.Register(() => ApplicationContainer.Dispose());
        }
 public static IApplicationBuilder UseWebJobsScriptHost(this IApplicationBuilder builder, IApplicationLifetime applicationLifetime)
 {
     return(UseWebJobsScriptHost(builder, applicationLifetime, null));
 }
Exemplo n.º 34
0
 public NetworkImuService(IApplicationLifetime applicationLifetime, ILogger <NetworkImuService> logger)
 {
     applicationLifetime.ApplicationStopping.Register(() => _keepGoing = false);
     _logger = logger;
     Task.Run((Action)HandleConnection);
 }
Exemplo n.º 35
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();

            appLifetime.ApplicationStopped.Register(() => this.ApplicationContainer.Dispose());
        }
 public HomeController(StatelessServiceContext context, FabricClient fabricClient, HttpClient httpClient, IApplicationLifetime appLifetime)
 {
     this.context      = context;
     this.fabricClient = fabricClient;
     this.httpClient   = httpClient;
     this.appLifetime  = appLifetime;
 }
        public IActionResult Restart([FromServices] IApplicationLifetime applicationLifetime)
        {
            applicationLifetime.StopApplication();

            return(Ok());
        }
        public static IApplicationBuilder UseWebJobsScriptHost(this IApplicationBuilder builder, IApplicationLifetime applicationLifetime, Action <WebJobsRouteBuilder> routes)
        {
            IEnvironment environment = builder.ApplicationServices.GetService <IEnvironment>() ?? SystemEnvironment.Instance;

            builder.UseMiddleware <EnvironmentReadyCheckMiddleware>();

            if (environment.IsPlaceholderModeEnabled())
            {
                builder.UseMiddleware <PlaceholderSpecializationMiddleware>();
            }

            // This middleware must be registered before we establish the request service provider.
            builder.UseWhen(context => !context.Request.IsAdminRequest(), config =>
            {
                config.UseMiddleware <HostAvailabilityCheckMiddleware>();
            });

            builder.UseMiddleware <HostWarmupMiddleware>();

            // This middleware must be registered before any other middleware depending on
            // JobHost/ScriptHost scoped services.
            builder.UseMiddleware <ScriptHostRequestServiceProviderMiddleware>();

            if (!environment.IsAppServiceEnvironment())
            {
                builder.UseMiddleware <AppServiceHeaderFixupMiddleware>();
            }

            builder.UseMiddleware <HttpExceptionMiddleware>();
            builder.UseMiddleware <ResponseBufferingMiddleware>();
            builder.UseMiddleware <HomepageMiddleware>();
            builder.UseWhen(context => !context.Request.IsAdminRequest(), config =>
            {
                config.UseMiddleware <HttpThrottleMiddleware>();
            });
            builder.UseMiddleware <FunctionInvocationMiddleware>();

            // Register /admin/vfs, and /admin/zip to the VirtualFileSystem middleware.
            builder.UseWhen(VirtualFileSystemMiddleware.IsVirtualFileSystemRequest, config => config.UseMiddleware <VirtualFileSystemMiddleware>());

            // Ensure the HTTP binding routing is registered after all middleware
            builder.UseHttpBindingRouting(applicationLifetime, routes);

            builder.UseMvc();

            return(builder);
        }
Exemplo n.º 39
0
        private void RegisterZipkinTrace(IApplicationBuilder app, ILoggerFactory loggerFactory, IApplicationLifetime lifetime)
        {
            lifetime.ApplicationStarted.Register(() =>
            {
                TraceManager.SamplingRate = 1.0f;
                var logger     = new TracingLogger(loggerFactory, "zipkin4net");
                var httpSender = new HttpZipkinSender("http://47.100.193.29:9411", "application/json");
                var tracer     = new ZipkinTracer(httpSender, new JSONSpanSerializer(), new Statistics());

                var consoleTracer = new zipkin4net.Tracers.ConsoleTracer();
                TraceManager.RegisterTracer(consoleTracer);
                TraceManager.RegisterTracer(tracer);
                TraceManager.Start(logger);
            });
            lifetime.ApplicationStopped.Register(() => TraceManager.Stop());
            app.UseTracing("User.Api");
        }
Exemplo n.º 40
0
 public ConsoleLifetime(IOptions <ConsoleLifetimeOptions> options, IHostingEnvironment environment, IApplicationLifetime applicationLifetime)
 {
     Options             = options?.Value ?? throw new ArgumentNullException(nameof(options));
     Environment         = environment ?? throw new ArgumentNullException(nameof(environment));
     ApplicationLifetime = applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime));
 }
Exemplo n.º 41
0
 public MigratorHost(Migrator migrator, IApplicationLifetime lifetime, ISemanticLog log)
     : base(lifetime, log)
 {
     this.migrator = migrator;
 }
Exemplo n.º 42
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime)
        {
            app.UseProcessEngine(lifetime);

            app.UseCors(cors =>
                        cors.AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowAnyOrigin());

            app.UseWorkflow();

            app.UseMvc();
        }
Exemplo n.º 43
0
 public SigtermHealthCheck(IApplicationLifetime applicationLifetime)
 {
     _applicationLifetime = applicationLifetime;
 }
Exemplo n.º 44
0
        //public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        //public void ConfigureServices(IServiceCollection services)
        //{
        //    // Add framework services.
        //    services.AddMvc();

        //}

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Aulabit API 0.001");
            });
            app.UseMvc();

            //app.UseSwaggerUi();
            appLifetime.ApplicationStopped.Register(() => this.ApplicationContainer.Dispose());
        }
Exemplo n.º 45
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            app.UseApplicationInsightsExceptionTelemetry();

            app.UseMvc();

            // Dispose of resources that have been resolved in the application container.
            appLifetime.ApplicationStopped.Register(() => this.ApplicationContainer.Dispose());
        }
Exemplo n.º 46
0
        public static IApplicationBuilder UseTestStuff(
            this IApplicationBuilder app,
            IApplicationLifetime lifetime,
            bool runSampleRequestsFromApp)
        {
            app.Use(
                (context, next) =>
            {
                RandomClientIdForTesting.SetTheFakeClaimsPrincipal(context);
                return(next());
            });

            var token = lifetime.ApplicationStopping;

            if (runSampleRequestsFromApp)
            {
                var apdexSamples = new AppMetricsTaskScheduler(
                    TimeSpan.FromSeconds(ApdexSamplesInterval),
                    () =>
                {
                    var satisfied   = HttpClient.GetAsync("api/satisfying", token);
                    var tolerating  = HttpClient.GetAsync("api/tolerating", token);
                    var frustrating = HttpClient.GetAsync("api/frustrating", token);

                    return(Task.WhenAll(satisfied, tolerating, frustrating));
                });

                apdexSamples.Start();

                var randomErrorSamples = new AppMetricsTaskScheduler(
                    TimeSpan.FromSeconds(RandomSamplesInterval),
                    () =>
                {
                    var randomStatusCode = HttpClient.GetAsync("api/randomstatuscode", token);
                    var randomException  = HttpClient.GetAsync("api/randomexception", token);

                    return(Task.WhenAll(randomStatusCode, randomException));
                });

                randomErrorSamples.Start();

                var testSamples = new AppMetricsTaskScheduler(
                    TimeSpan.FromSeconds(GetEndpointSuccessInterval),
                    () =>
                {
                    var testOne = HttpClient.GetAsync("api/test", token);
                    var testTwo = HttpClient.GetAsync("api/test/params/abc/123", token);

                    return(Task.WhenAll(testOne, testTwo));
                });

                testSamples.Start();

                var slaSamples = new AppMetricsTaskScheduler(
                    TimeSpan.FromSeconds(SlaEndpointsInterval),
                    () => HttpClient.GetAsync("api/slatest/timer", token));

                slaSamples.Start();

                var randomBufferGenerator = new RandomBufferGenerator(50000);
                var postPutSamples        = new AppMetricsTaskScheduler(
                    TimeSpan.FromSeconds(PutAndPostRequestsInterval),
                    () =>
                {
                    var putBytes    = new ByteArrayContent(randomBufferGenerator.GenerateBufferFromSeed());
                    var putFormData = new MultipartFormDataContent {
                        { putBytes, "put-file", "rnd-put" }
                    };
                    var putRequest = HttpClient.PutAsync("api/file", putFormData, token);

                    var postBytes    = new ByteArrayContent(randomBufferGenerator.GenerateBufferFromSeed());
                    var postFormData = new MultipartFormDataContent {
                        { postBytes, "post-file", "rnd-post" }
                    };
                    var postRequest = HttpClient.PostAsync("api/file", postFormData, token);

                    return(Task.WhenAll(putRequest, postRequest));
                });

                postPutSamples.Start();
            }

            return(app);
        }
Exemplo n.º 47
0
 public OpenShiftCertificateExpiration(IOptions <OpenShiftIntegrationOptions> options, OpenShiftCertificateLoader certificateLoader, IApplicationLifetime applicationLifetime, ILogger <OpenShiftCertificateExpiration> logger)
 {
     _options             = options;
     _certificateLoader   = certificateLoader;
     _applicationLifetime = applicationLifetime;
     _logger = logger;
 }
Exemplo n.º 48
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            MongoConfigurator.Initialize();
            var generalSettings = app.ApplicationServices.GetService <GeneralSettings>();

            if (generalSettings.SeedData)
            {
                var dataInitializer = app.ApplicationServices.GetService <IDataInitializer>();
                dataInitializer.SeedAsync();
            }


            app.UseSession(); //23-03


            app.UseAuthentication();
            app.UseCors(
                options => options.WithOrigins("https://localhost:8080")
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
                );

            app.UseHttpsRedirection(); //
            app.UseHsts();             //

            //         app.UseCors(builder => builder
            // .WithOrigins("http://localhost:8080")
            // .AllowAnyMethod()
            // .AllowAnyHeader()
            // .AllowCredentials()
            // );
            app.UseMvc();
            appLifetime.ApplicationStopped.Register(() => ApplicationContainer.Dispose());
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            ExtensionsLogger.Use(loggerFactory);

            app.UseMvc();

            Services = app.ApplicationServices;

            // start micro services
            applicationLifetime.ApplicationStarted.Register(OnStart);
            applicationLifetime.ApplicationStopping.Register(OnStopping);
            applicationLifetime.ApplicationStopped.Register(OnStopped);
        }
Exemplo n.º 50
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public async void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider, IApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();

            // stash an applicant's user data in redis for test purposes...this would simulate establishing auth/session in the real world
            var identityRepository = serviceProvider.GetService <IIdentityRepository>();
            await identityRepository.UpdateUserAsync(new User { Id = "1", Email = "*****@*****.**", Name = "Josh Dillinger" });

            var bus       = ApplicationContainer.Resolve <IBusControl>();
            var busHandle = TaskUtil.Await(() => bus.StartAsync());

            lifetime.ApplicationStopping.Register(() => busHandle.Stop());
        }
Exemplo n.º 51
0
 public ServiceBaseLifetime(IApplicationLifetime applicationLifetime)
 {
     this.delayStart          = new TaskCompletionSource <object>();
     this.applicationLifetime =
         applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime));
 }
Exemplo n.º 52
0
 public HelloWorldClientHostedService(IClusterClient client, IApplicationLifetime lifetime)
 {
     _client = client;
 }
        public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IApplicationLifetime lifetime, ConsulOption consulOption)
        {
            var consulClient = new ConsulClient(x =>
            {
                // consul 服务地址
                x.Address = new Uri(consulOption.Address);
            });

            var registration = new AgentServiceRegistration()
            {
                ID      = Guid.NewGuid().ToString(),
                Name    = consulOption.ServiceName, // 服务名
                Address = consulOption.ServiceIP,   // 服务绑定IP
                Port    = consulOption.ServicePort, // 服务绑定端口
                Check   = new AgentServiceCheck()
                {
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), //服务启动多久后注册
                    Interval = TimeSpan.FromSeconds(10),                      //健康检查时间间隔
                    HTTP     = consulOption.ServiceHealthCheck,               //健康检查地址
                    Timeout  = TimeSpan.FromSeconds(5)
                }
            };

            // 服务注册
            consulClient.Agent.ServiceRegister(registration).Wait();

            // 应用程序终止时,服务取消注册
            lifetime.ApplicationStopping.Register(() =>
            {
                consulClient.Agent.ServiceDeregister(registration.ID).Wait();
            });
            return(app);
        }
Exemplo n.º 54
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider, IApplicationLifetime lifetime)
        {
            var dbContext       = serviceProvider.GetService <AppDbContext>();
            var settingsOptions = serviceProvider.GetService <IOptions <AppConfig> >();
            var appConfig       = settingsOptions.Value;

            app.UseCors("AllowAll");
            app.UseAuthentication();

            #region Authorization Middleware
            var apiGateway = Configuration["APIGatewayServer"];
            app.Use(AuthorizeMiddleWare.Authorize(apiGateway));
            #endregion

            app.UseMvc();

            #region App Init
            {
                var serverId   = Configuration["GuidSettings:ServerId"];
                var guidSalt   = Configuration["GuidSettings:GuidSalt"];
                var guidMinLen = Configuration["GuidSettings:GuidMinLen"];
                GuidGen.Init(serverId, guidSalt, guidMinLen);
            }
            #endregion

            #region Database Init
            {
                dbContext.Database.Migrate();
                DatabaseInitTool.InitDatabase(app, env, serviceProvider, dbContext);
            }
            #endregion
        }
Exemplo n.º 55
0
 public InventoryClientHostedService(IClusterClient client, IApplicationLifetime lifetime)
 {
     _client = client;
 }
Exemplo n.º 56
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
        {
            app.UseExceptionHandler(options =>
            {
                options.Run(async context =>
                {
                    var exceptionHandler = context.Features.Get <IExceptionHandlerFeature>();

                    if (exceptionHandler != null && exceptionHandler.Error != null)
                    {
                        await Task.Run(() => Log.ForContext("Exception", exceptionHandler.Error, true).Error("{Message}", exceptionHandler.Error.Message));
                    }
                });
            });


            var sw = new Stopwatch();

            appLifetime.ApplicationStarted.Register(LogApplicationStarted);

            appLifetime.ApplicationStopped.Register(LogApplicationStopped);

            app.UseMiddleware <LogMiddleware>();

            app.UseMiddleware <AuthenticationMiddleware>();

            app.UseMvc();

            // Enable Swagger
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "Hub Transactions API v1");
            });

            var enableMigration = Configuration["EnableReportingPostgreSQLMigration"].ToBool();

            if (enableMigration)
            {
                var connectionString = Configuration.GetConnectionString("ReportingPostgreSQLConnectionString");
                var database         = new Database(connectionString, "Npgsql");

                Migrator
                .ForDatabase(new PostgreSQLMigrationDatabase(database))
                .WithPath(Path.Combine(env.ContentRootPath, "Migrations"))
                .Migrate();
            }
        }
Exemplo n.º 57
0
 public static void RegisterActorSystem(this IApplicationLifetime lifetime, IApplicationBuilder app)
 {
     lifetime.ApplicationStarted.Register(() => app.ApplicationServices.GetService <ActorSystem>());
     lifetime.ApplicationStopping.Register(() => app.ApplicationServices.GetService <ActorSystem>().Terminate().Wait());
 }
 public FramingModeHandshakeMiddleware(HandshakeDelegate next, IApplicationLifetime appLifetime)
 {
     _next        = next;
     _appLifetime = appLifetime;
 }
Exemplo n.º 59
0
        public static IApplicationBuilder RegisterWithConsul(this IApplicationBuilder app, Uri uri, IApplicationLifetime lifetime)
        {
            var consulClient   = app.ApplicationServices.GetRequiredService <IConsulClient>();
            var consulConfig   = app.ApplicationServices.GetRequiredService <IOptions <ConsulConfig> >();
            var loggingFactory = app.ApplicationServices.GetRequiredService <ILoggerFactory>();
            var logger         = loggingFactory.CreateLogger <IApplicationBuilder>();

            var tcpCheck = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1),
                Interval = TimeSpan.FromSeconds(30),
                TCP      = $"{uri.Host}:{uri.Port}"
            };

            var httpCheck = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1),
                Interval = TimeSpan.FromSeconds(30),
                HTTP     = $"{uri.Scheme}://{uri.Host}:{uri.Port}/healthcheck"
            };

            var registration = new AgentServiceRegistration
            {
                ID      = $"{consulConfig.Value.ServiceId}-{uri.Port}",
                Name    = consulConfig.Value.ServiceName,
                Address = $"{uri.Host}",
                Port    = uri.Port,
                Tags    = new[] { "WebApp" },
                Checks  = new[] { tcpCheck, httpCheck }
            };

            logger.LogInformation("Registering with Consul");
            consulClient.Agent.ServiceDeregister(registration.ID).Wait();
            consulClient.Agent.ServiceRegister(registration).Wait();

            lifetime.ApplicationStopping.Register(() =>
            {
                logger.LogInformation("Deregistering from Consul");
                consulClient.Agent.ServiceDeregister(registration.ID).Wait();
            });

            return(app);
        }
Exemplo n.º 60
0
        public static IApplicationBuilder registerConsul(this IApplicationBuilder app, IApplicationLifetime lifetime)
        {
            var consulClient = app.ApplicationServices
                               .GetRequiredService <IConsulClient>();

            var consulConfig = app.ApplicationServices
                               .GetRequiredService <IOptions <ConsulConfig> >();

            var loggingFactory = app.ApplicationServices
                                 .GetRequiredService <ILoggerFactory>();

            var logger = loggingFactory.CreateLogger <IApplicationBuilder>();

            var features  = app.Properties["server.Features"] as FeatureCollection;
            var addresses = features.Get <IServerAddressesFeature>();
            var address   = addresses.Addresses.First();

            var uri = new Uri(address);

            AgentServiceCheck[] checks = new AgentServiceCheck[1];
            checks[0] = new AgentServiceCheck()
            {
                HTTP     = $"{uri.Scheme}://{uri.Host}:{uri.Port}/api/health/status",
                Timeout  = TimeSpan.FromSeconds(3),
                Interval = TimeSpan.FromSeconds(10)
            };

            var registration = new AgentServiceRegistration()
            {
                ID      = $"{consulConfig.Value.ServiceID}-{uri.Port}",
                Name    = consulConfig.Value.ServiceName,
                Address = $"{uri.Scheme}://{uri.Host}",
                Port    = uri.Port,
                Tags    = new[] { "Security" },
                Checks  = checks
            };

            logger.LogInformation("Registering with Consul");
            consulClient.Agent.ServiceDeregister(registration.ID).Wait();
            consulClient.Agent.ServiceRegister(registration).Wait();

            lifetime.ApplicationStopping.Register(() =>
            {
                logger.LogInformation("Deregistering from Consult");
                consulClient.Agent.ServiceDeregister(registration.ID).Wait();
            });

            return(app);
        }