public static void Run(IHostedService service, string[] args) { var consoleArg = Array.Find(args, arg => string.Equals(arg, "/console", StringComparison.CurrentCultureIgnoreCase)); var host = consoleArg != null ? (IServiceHost) new ConsoleServiceHost() : new WindowsServiceHost(); host.Run(service); }
public void Run(IHostedService service) { _service = service; ServiceName = _service.Name; Logger.SetLogger(new EventLogLogger(EventLog)); _service.Attach(this); Run(this); }
public override void SetUp() { base.SetUp(); workitemWriterMock = Repository.StrictMock<WorkitemWriter>(); eventManagerMock = Repository.StrictMock<IEventManager>(); eventManager = new EventManager(); service = new WorkitemWriterHostedService(); service.Initialize(null, eventManager, null); }
public void Run(IHostedService service) { if (service == null) { throw new ArgumentNullException(nameof(service)); } _service = service; ServiceName = _service.Name; Logger.SetLogger(new EventLogLogger(EventLog)); _service.Attach(this); Run(this); }
public QueuedHostedServiceTest() { var logger = new NullLogger <QueuedHostedService>(); var services = new ServiceCollection(); services.AddBackgroundQueue(); services.AddSingleton <ILogger <QueuedHostedService> >(logger); var serviceProvider = services.BuildServiceProvider(); BackgroundQueue = serviceProvider.GetService <IBackgroundTaskQueue>(); HostedService = serviceProvider.GetService <IHostedService>(); }
public TasksMessagingServiceTests() { _eventConnectionContextMock = new Mock <IEventConnectionContext>(); _taskEventAccessorMock = new Mock <ITaskEventAccessor>(); _eventScopeMock = new Mock <IEventScope>(); _tasksHubStorage = new Mock <ITasksHubUsersStorage>(); _hubClientMock = new Mock <IHubClient <TasksHub> >(); _eventConnectionContextMock.Setup(x => x.EventScope()).Returns(_eventScopeMock.Object); _tasksHubStorage.Setup(x => x.Get(ProjectId, CreatorId)).Returns(_connectionIds); _messagingService = new TasksMessagingService(_eventConnectionContextMock.Object, _taskEventAccessorMock.Object, _hubClientMock.Object, _tasksHubStorage.Object); }
public void Start() { IoC.Container.Install(FromAssembly.This()); hostedService = IoC.Container.Resolve<IHostedService>(); startEvents = IoC.Container.ResolveAll<IStartServiceEvent>(); stopEvents = IoC.Container.ResolveAll<IStopServiceEvent>(); foreach (var startServiceEvent in startEvents.OrderBy(e => e.Order)) { startServiceEvent.Execute(); } hostedService.Start(); }
public void Run(IHostedService service) { service.Attach(this); Logger.Log(string.Format("Starting service {0}...", service.Name)); service.Start(); Logger.Log("Service started."); ConsoleKeyInfo key; do { key = Console.ReadKey(true); } while (key.Key != ConsoleKey.D || key.Modifiers != ConsoleModifiers.Control); Logger.Log(string.Format("Stopping service {0}...", service.Name)); service.Stop(); Logger.Log("Service stopped."); }
public void Start() { IoC.Container.Install(FromAssembly.This()); hostedService = IoC.Container.Resolve <IHostedService>(); startEvents = IoC.Container.ResolveAll <IStartServiceEvent>(); stopEvents = IoC.Container.ResolveAll <IStopServiceEvent>(); foreach (var startServiceEvent in startEvents.OrderBy(e => e.Order)) { startServiceEvent.Execute(); } hostedService.Start(); }
/// <summary>启动服务</summary> /// <param name="service"></param> public override void Run(IHostedService service) { if (service == null) { throw new ArgumentNullException(nameof(service)); } _service = service; var source = new CancellationTokenSource(); service.StartAsync(source.Token); // 阻塞 Thread.Sleep(-1); }
public static async Task Main(string[] args) { var basePath = PlatformServices.Default.Application.ApplicationBasePath; if (basePath.ToLower().Contains("inventorymanagementqa")) { var builderRunAsService = new HostBuilder() .ConfigureServices((hostContext, services) => { services.AddHostedService <WindowsServiceHost>(); }); await builderRunAsService.RunAsServiceAsync(); } else { StartUpConfiguration startUpConfiguration = new StartUpConfiguration(); startUpConfiguration.Startup(); IHostedService sendInventoryManagementMessages = startUpConfiguration.SendingHostedService(); IHostedService receiveInventoryManagementMessages = startUpConfiguration.ReceivingHostedService(); IHostedService processMessages = startUpConfiguration.ProcessMessagesHostedService(); var builder = new HostBuilder().ConfigureAppConfiguration((hostingContext, config) => { }) .ConfigureServices((hostContext, services) => { services.AddTransient <IHostedService>(provider => processMessages); }) .ConfigureServices((hostContext, services) => { services.AddTransient <IHostedService>(provider => sendInventoryManagementMessages); }) .ConfigureServices((hostContext, services) => { services.AddTransient <IHostedService>(provider => receiveInventoryManagementMessages); }) .ConfigureLogging((hostingContext, logging) => { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); }); builder.RunConsoleAsync().Wait(); } }
private Task StartHostedService(bool runOnce, [NotNull] IHostedService process, string name) { // Run the hosted process, wrapped in polly retry logic. return(BuildWrappedPolicy().ExecuteAndCaptureAsync(process.StartAsync, _cancellation.Token) .ContinueWith(p => { if (p.IsFaulted) { _logger?.LogError(p.Exception, $"Error running hosted process {name} execution {p.Exception?.Message}"); ProcessError(null, p.Exception, !runOnce); } if (p.Status == TaskStatus.Canceled) { _logger?.LogWarning("Hosted process cancelled"); } })); }
public async Task FromException() { Routable routable = null; this.errorComponent.Reset(); this.errorComponent.Setup(x => x.Process(It.IsAny <Routable>())).Callback((Routable x) => { routable = x; }); this.processComponent.Reset(); IHostedService service = this.GetHostedService(true); await service.StartAsync(CancellationToken.None); await service.StopAsync(CancellationToken.None); Assert.IsNull(routable); }
public async Task ErrorComponentErrors() { Routable routable = null; this.errorComponent.Reset(); this.errorComponent.Setup(x => x.Process(It.IsAny <Routable>())).Callback((Routable x) => { routable = x; throw new ProcessException("Manual Error", new IndexOutOfRangeException("Random index")); }); IHostedService service = this.GetHostedService(false, false, true); await service.StartAsync(CancellationToken.None); await service.StopAsync(CancellationToken.None); Assert.IsTrue(this.IsInError(routable, "Error Component")); }
public async Task AtomicError() { Routable routable = null; this.errorComponent.Reset(); this.errorComponent.Setup(x => x.Process(It.IsAny <Routable>())).Callback((Routable x) => { routable = x; }); this.processComponent.Reset(); IHostedService service = this.GetHostedService(false, false, true); await service.StartAsync(CancellationToken.None); await service.StopAsync(CancellationToken.None); Assert.IsTrue(this.IsInError(routable, "Atomic Component")); }
public async Task CanRunDIComponent() { AutoResetEvent autoResetEvent = new AutoResetEvent(false); Routable routable = null; this.diProcessor.Reset(); this.diProcessor.Setup(x => x.Process(It.IsAny <Routable>())).Callback((Routable x) => { routable = x; }); IHostedService service = this.SetupDIComponent(); await service.StartAsync(CancellationToken.None); autoResetEvent.WaitOne(TimeSpan.FromSeconds(5)); await service.StopAsync(CancellationToken.None); Assert.AreEqual("Yes", routable.Headers["ComponentRan"]); }
public DeviceManagerFactory(IHostingEnvironment env, IOptionsMonitor <PlayerConfiguration> playerConfigurationOptions, IHostedService hs, ILoggerFactory lf) { this.env = env; this.schedulerService = hs as SchedulerService; managers = new Dictionary <DeviceIdentifier, DeviceManager>(new DeviceComparer()); loggerFactory = lf; log = loggerFactory.CreateLogger <DeviceManagerFactory>(); musicServerUrl = null; this.playerConfiguration = playerConfigurationOptions.CurrentValue; playerConfigurationOptions.OnChangeWithDelay((opt) => { this.playerConfiguration = opt; foreach (var item in managers) { item.Value.ReplacePlayConfiguration(this.playerConfiguration); } }); }
public void Run(IHostedService service) { if (service == null) { throw new ArgumentNullException(nameof(service)); } service.Attach(this); Logger.Log(string.Format("Starting service {0}...", service.Name)); service.Start(); Logger.Log("Service started."); ConsoleKeyInfo key; do { key = Console.ReadKey(true); } while (key.Key != ConsoleKey.D || key.Modifiers != ConsoleModifiers.Control); Logger.Log(string.Format("Stopping service {0}...", service.Name)); service.Stop(); Logger.Log("Service stopped."); }
public TestBase() { var services = new ServiceCollection(); var configuration = ConfigurationRootCreator.Create(services); services.Configure <RabbitMqOption>(configuration); services.ConfigureBus(); services.AddSingleton <ISubscribeSynchronousToAll, RabbitMqEventPublisher>(); Resolver = EventFlowOptions.New .UseServiceCollection(services) .RegisterModule <BookingDomainModule>() .RegisterModule <CommandModule>() .RegisterModule <CommandHandlersModule>() .RegisterServices(r => r.Register <IDbContextProvider <EventStoreContext>, FakedEventStoreContextProvider>()) .CreateResolver(false); CommandBus = Resolver.Resolve <ICommandBus>(); HostedService = Resolver.Resolve <IHostedService>(); }
public void Register <T>(IHostedService service, string friendlyName) where T : class, IHostedService { if (typeof(T) != service.GetType()) { throw new ArgumentException($"Type mismatch: {nameof(T)} is {typeof(T).Name}, but {nameof(service)} is {service.GetType()}."); } if (IsStartAllAsyncStarted) { throw new InvalidOperationException("Services are already started."); } lock (ServicesLock) { if (AnyNoLock <T>()) { throw new InvalidOperationException($"{typeof(T).Name} is already registered."); } Services.Add(new HostedService(service, friendlyName)); } }
public async Task ComponentError() { Routable routable = null; this.errorComponent.Reset(); this.errorComponent.Setup(x => x.Process(It.IsAny <Routable>())).Callback((Routable x) => { routable = x; }); this.processComponent.Reset(); this.processComponent.Setup(x => x.Process(It.IsAny <Routable>())).Callback((Routable x) => { throw new Kyameru.Core.Exceptions.ProcessException("Manual Error"); }); IHostedService service = this.GetHostedService(); await service.StartAsync(CancellationToken.None); await service.StopAsync(CancellationToken.None); Assert.IsTrue(this.IsInError(routable, "Processing component")); }
public static void Initialize(TestContext context) { var pollerConfig = new PollerConfig { Interval = TimeSpan.Zero, WatchedUserIds = new [] { "mockuser" }, StoreSentUpdates = true }; IServiceCollection addHostedService = new ServiceCollection() .AddLogging(builder => builder.AddTestsLogging(context)) .AddUpdatesProducerMockRepositories() .AddSingleton <IUpdatesPublisher, MockUpdatesPublisher>() .AddSingleton <IUpdatesProvider, MockUpdatesProvider>() .AddUpdatesPollerService(pollerConfig); var services = addHostedService .BuildServiceProvider(); _publisher = (MockUpdatesPublisher)services.GetService <IUpdatesPublisher>(); _service = services.GetService <IHostedService>(); }
private CommandLineBackgroundServiceUnit(Action <IServiceCollection> configureDelegate, string[] args) { Reporter = new TestReporter(); IServiceCollection collection = new ServiceCollection(); configureDelegate?.Invoke(collection); IServiceProviderFactory <IServiceCollection> factory = new DefaultServiceProviderFactory(); IServiceProvider provider = factory.CreateServiceProvider(collection); IHostApplicationLifetime appLifetime = new TestApplicationLifetime(() => { StopCount++; commandPipelineOperation.SetResult(true); }); Assembly assembly = typeof(CommandLineBackgroundServiceUnit).Assembly; context = new CommandContext(args, assembly); hostedService = new CommandLineBackgroundService(provider, appLifetime, context, Reporter); commandPipelineOperation = new TaskCompletionSource <bool>(); }
private Task createTask(IHostedService service, CancellationToken cancellationToken) { cancellationToken.Register(service.Cancel); return new Task(service.Start, cancellationToken, TaskCreationOptions.LongRunning); }
public Guid Install(IHostedService service) { this.WriteDebugMessage(string.Format("Installing hosted service {0}({1}).", service.GetType().Name, service.Name)); var serviceId = Guid.NewGuid(); var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; var task = createTask(service, cancellationToken); _taskMap.Add(serviceId, task); _taskTokenSources.Add(serviceId, cancellationTokenSource); Services.Add(serviceId, service); this.WriteInfoMessage(string.Format("Installed hosted service {0}.", service.Name)); return serviceId; }
public ValuesController(IHostedService listenerService) { this.listenerService = listenerService; }
public void Startup() { // // get configuration information // MessageQueueAppConfig messageQueueAppConfig = new MessageQueueAppConfig(); ConnectionStrings connectionStrings = new ConnectionStrings(); var basePath = PlatformServices.Default.Application.ApplicationBasePath; if (basePath.ToLower().Contains("salesordermanagementqa")) { CodeProject.Shared.Common.Models.AppSettings.MessageQueueAppSettings appSettings = new CodeProject.Shared.Common.Models.AppSettings.MessageQueueAppSettings(); string readContents; using (StreamReader streamReader = new StreamReader(basePath + @"\AppSettings.QA.json", Encoding.UTF8)) { readContents = streamReader.ReadToEnd(); } appSettings = CodeProject.Shared.Common.Utilities.SerializationFunction <CodeProject.Shared.Common.Models.AppSettings.MessageQueueAppSettings> .ReturnObjectFromString(readContents); messageQueueAppConfig.MessageQueueHostName = appSettings.MessageQueueAppConfig.MessageQueueHostName; messageQueueAppConfig.MessageQueueUserName = appSettings.MessageQueueAppConfig.MessageQueueUserName; messageQueueAppConfig.MessageQueuePassword = appSettings.MessageQueueAppConfig.MessageQueuePassword; messageQueueAppConfig.MessageQueueEnvironment = appSettings.MessageQueueAppConfig.MessageQueueEnvironment; messageQueueAppConfig.ExchangeName = appSettings.MessageQueueAppConfig.ExchangeName; messageQueueAppConfig.RoutingKey = appSettings.MessageQueueAppConfig.RoutingKey; messageQueueAppConfig.InboundMessageQueue = appSettings.MessageQueueAppConfig.InboundMessageQueue; messageQueueAppConfig.OutboundMessageQueues = appSettings.MessageQueueAppConfig.OutboundMessageQueues; messageQueueAppConfig.LoggingExchangeName = appSettings.MessageQueueAppConfig.LoggingExchangeName; messageQueueAppConfig.LoggingMessageQueue = appSettings.MessageQueueAppConfig.LoggingMessageQueue; messageQueueAppConfig.OriginatingQueueName = appSettings.MessageQueueAppConfig.OriginatingQueueName; messageQueueAppConfig.SendToLoggingQueue = appSettings.MessageQueueAppConfig.SendToLoggingQueue; messageQueueAppConfig.AcknowledgementMessageExchangeSuffix = appSettings.MessageQueueAppConfig.AcknowledgementMessageExchangeSuffix; messageQueueAppConfig.AcknowledgementMessageQueueSuffix = appSettings.MessageQueueAppConfig.AcknowledgementMessageQueueSuffix; messageQueueAppConfig.TriggerExchangeName = appSettings.MessageQueueAppConfig.TriggerExchangeName; messageQueueAppConfig.TriggerQueueName = appSettings.MessageQueueAppConfig.TriggerQueueName; messageQueueAppConfig.QueueImmediately = appSettings.MessageQueueAppConfig.QueueImmediately; messageQueueAppConfig.InboundSemaphoreKey = appSettings.MessageQueueAppConfig.InboundSemaphoreKey; messageQueueAppConfig.OutboundSemaphoreKey = appSettings.MessageQueueAppConfig.OutboundSemaphoreKey; messageQueueAppConfig.ProcessingIntervalSeconds = appSettings.MessageQueueAppConfig.ProcessingIntervalSeconds; messageQueueAppConfig.SendingIntervalSeconds = appSettings.MessageQueueAppConfig.SendingIntervalSeconds; messageQueueAppConfig.ReceivingIntervalSeconds = appSettings.MessageQueueAppConfig.ReceivingIntervalSeconds; messageQueueAppConfig.SignalRHubUrl = appSettings.MessageQueueAppConfig.SignalRHubUrl; messageQueueAppConfig.RunAsService = appSettings.MessageQueueAppConfig.RunAsService; connectionStrings.PrimaryDatabaseConnectionString = appSettings.ConnectionStrings.PrimaryDatabaseConnectionString; using (var sw = File.AppendText(Path)) { sw.WriteLine("HostName=" + messageQueueAppConfig.MessageQueueHostName + "*"); } } else { string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); string jsonFile = $"AppSettings.{environment}.json"; var configBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(jsonFile, optional: true, reloadOnChange: true); IConfigurationRoot configuration = configBuilder.Build(); configuration.GetSection("MessageQueueAppConfig").Bind(messageQueueAppConfig); configuration.GetSection("ConnectionStrings").Bind(connectionStrings); } // // set up sending queue // IMessageQueueConnection sendingQueueConnection = new MessageQueueConnection(messageQueueAppConfig); sendingQueueConnection.CreateConnection(); List <IMessageQueueConfiguration> messageQueueConfigurations = new List <IMessageQueueConfiguration>(); IMessageQueueConfiguration salesOrderSubmittedConfiguration = new MessageQueueConfiguration(MessageQueueExchanges.SalesOrderSubmitted, messageQueueAppConfig, sendingQueueConnection); salesOrderSubmittedConfiguration.AddQueue(MessageQueueEndpoints.InventoryQueue); salesOrderSubmittedConfiguration.AddQueue(MessageQueueEndpoints.LoggingQueue); salesOrderSubmittedConfiguration.InitializeOutboundMessageQueueing(); messageQueueConfigurations.Add(salesOrderSubmittedConfiguration); ISalesOrderManagementDataService salesOrderManagementDataService = new SalesOrderManagementDataService(); IMessageQueueProcessing messageProcessing = new MessageProcessing(salesOrderManagementDataService); _sendSalesOrderManagementMessages = new SendMessages(sendingQueueConnection, messageProcessing, messageQueueAppConfig, connectionStrings, messageQueueConfigurations, MessageQueueEndpoints.SalesOrderQueue); // // set up receiving queue // IMessageQueueConnection receivingConnection = new MessageQueueConnection(messageQueueAppConfig); receivingConnection.CreateConnection(); List <IMessageQueueConfiguration> inboundMessageQueueConfigurations = new List <IMessageQueueConfiguration>(); IMessageQueueConfiguration inboundConfiguration = new MessageQueueConfiguration(messageQueueAppConfig, receivingConnection); inboundMessageQueueConfigurations.Add(inboundConfiguration); inboundConfiguration.InitializeInboundMessageQueueing(MessageQueueEndpoints.SalesOrderQueue); inboundConfiguration.InitializeLoggingExchange(MessageQueueExchanges.Logging, MessageQueueEndpoints.LoggingQueue); ISalesOrderManagementDataService inboundSalesOrderManagementDataService = new SalesOrderManagementDataService(); IMessageQueueProcessing inboundMessageProcessing = new MessageProcessing(inboundSalesOrderManagementDataService); _receiveSalesOrderManagementMessages = new ReceiveMessages(receivingConnection, inboundMessageProcessing, messageQueueAppConfig, connectionStrings, inboundMessageQueueConfigurations); // // Set Up Message Processing // ISalesOrderManagementDataService salesOrderManagementProcessingDataService = new SalesOrderManagementDataService(); IMessageQueueProcessing messageProcessor = new MessageProcessing(salesOrderManagementProcessingDataService); _processMessages = new ProcessMessages(messageProcessor, messageQueueAppConfig, connectionStrings); var builder = new HostBuilder().ConfigureAppConfiguration((hostingContext, config) => { }) .ConfigureServices((hostContext, services) => { services.AddTransient <IHostedService>(provider => _sendSalesOrderManagementMessages); }) .ConfigureServices((hostContext, services) => { services.AddTransient <IHostedService>(provider => _processMessages); }) .ConfigureServices((hostContext, services) => { services.AddTransient <IHostedService>(provider => _receiveSalesOrderManagementMessages); }); }
public ErrorHandlingMiddleware(RequestDelegate next, IHostingEnvironment environment, IHostedService loggingService) { _environment = environment; _loggingService = loggingService as LoggingService; this.next = next; }
public HostedService(IHostedService service, string friendlyName) { Service = Guard.NotNull(nameof(service), service); FriendlyName = Guard.NotNull(nameof(friendlyName), friendlyName); }
public ValuesController(IHubContext <ValuesHub> hub, IHostedService hostedService) { _hostedService = hostedService as GenerateRandom; }
public ConfigureBackups(ILoggerFactory loggerFactory, WebDbContextFactory dbf, IHostedService hostedService, IOptionsMonitor <ServiceOptions> options) : base(loggerFactory) { //log.LogInformation("Configuration constructor called"); this.dbf = dbf; //dbf.GetWebDbContext<ServiceDb>().Database.EnsureCreated(); this.options = options.CurrentValue; this.schedulerService = hostedService as SchedulerService; options.OnChangeWithDelay((opt) => { this.options = opt; SetupPipeline(); log.LogInformation("Configuration (appsettings) changed, starting ConfigureBackups"); this.schedulerService.ExecuteNow <ConfigureBackups>(); }); var backupSchedule = this.options.ServiceSchedules?.FirstOrDefault(sc => string.Compare(sc.Name, this.GetType().Name) == 0); schedule = backupSchedule?.Schedule ?? "0 0 1 */12 *";// default is At 00:00 AM, on day 1 of the month, every 12 months!! not useful! SetupPipeline(); }
public void OnStop_stops_started_hosted_service([Frozen] IServiceProvider services, WindowsService sut, IHostedService hostedService, HostControl control) { Mock.Get(services).Setup(p => p.GetService(typeof(IEnumerable <IHostedService>))).Returns(new[] { hostedService }); sut.OnStart(control); sut.OnStop(control); Mock.Get(hostedService).Verify(p => p.StopAsync(It.IsAny <CancellationToken>())); }
public ValuesController(RandomStringProvider randomStringProvider, IHostedService dataRefreshService) { _randomStringProvider = randomStringProvider; _dataRefreshService = dataRefreshService; }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime, IConsulClient consulClient, IHostedService hostedService) { loggerFactory.AddConsole(); var _logger = loggerFactory.CreateLogger <Startup>(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); app.UseSwagger(c => { c.PreSerializeFilters.Add((swagger, httpReq) => swagger.Host = httpReq.Host.Value); }); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs"); }); lifetime.ApplicationStopping.Register(() => { _logger.LogInformation("Deregistering from Consul"); try { hostedService.StopAsync(new CancellationToken()); } catch (Exception ex) { _logger.LogError(ex, $"Deregisteration failed"); } }); app.Map("/health", appBulider => { appBulider.Run(async context => await context.Response.WriteAsync("health")); }); app.UseWelcomePage(); }
internal HostedServiceWrapper(IHostedService inner, ILogger <HostedServiceWrapper> logger) { _inner = inner; _logger = logger; Name = inner.GetType().Name.Replace("HostedService", ""); }
public TrainingService(IDatabaseRepository <TrainingSession> trainingRepository, IHostedService hostedService) { this.trainingRepository = trainingRepository; this.hostedService = hostedService; }
public HostedServiceWrapper(TService hostedService) { _hostedService = (IHostedService)hostedService; }