Ajay
Ajay

Reputation: 3

How I can pass data to Worker Service in ( .Net core 6) from Web API .Net core 5

I am writing a worker service in Net core 6 and I want to call the worker service from API and pass sone data to worker service.

My Worker service code is as below:

``

IHost host = Host.CreateDefaultBuilder(args)
     .UseWindowsService(options =>
     {
         options.ServiceName = "TestWindowService";
     })
    .ConfigureServices(services =>
    {
        services.AddHostedService<ServiceWorker>();
        services.AddTransient<ITestService, TestService>();
        services.AddTransient<IDatabaseClientService, DatabaseClientService>();
    })
   .Build();
   
   await host.RunAsync();

``

I am calling Worker service from API and want to pass some data to Worker Service:

I tried this code from API but it is not working:

``

 ServiceController service = new ServiceController();
            service.MachineName = ".";
            service.ServiceName = this.WindowServiceName;

            if (service.Status != ServiceControllerStatus.Running)
                service.Start(new string[] { "Testargs" });

`` How can I pass data from API to worker service? I tried the above code, but it is not working. Once the service is running then I want to pass data to it again.

Upvotes: 0

Views: 677

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457147

You should use a message queue, such as Azure Storage Queues / Amazon Simple Queue Service / Google Cloud Tasks. On-premise solutions also exist, such as Kafka.

The idea is that the API serializes a message and sends it to the message queue before returning an HTTP response. The background service reads from that queue and handles those messages. I have more information about this pattern in my blog posts on basic distributed architecture and queues in particular.

Upvotes: 1

Related Questions