Search code examples
dapr

How to implement Dapr Subscriber in .net Windows Service?


I need to implement the Dapr Subscriber in the windows service, I am able to implement it in Asp.Net API. But not in Windows service, Is there any workaround to do this?


Solution

  • There is a trick to implementing this in windows service.

    We need to add a controller

    [ApiController]
    public class DaprController : ControllerBase
    {
    
        public DaprController()
        {
        }
    
        [Topic("pubSubName", "topicName")]
        [HttpPost("/topicName")]
        public ActionResult ProcessData([FromBody] string data)
        {
            return Ok();
        }
    }
    

    Also, we need to add a startup.cs file like this.

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    
    namespace Publisher
    {
        public class Startup
        {
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllers().AddDapr();
                services.AddLogging();
            }
    
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.UseCloudEvents();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                    endpoints.MapSubscribeHandler();
                });
            }
        }
    }
    

    And add the below code in the Program.cs file.

    .ConfigureWebHostDefaults((builder) =>
                    {
                        builder.UseStartup<Startup>();
                    })
    

    Reference: https://learn.microsoft.com/en-us/dotnet/architecture/dapr-for-net-developers/publish-subscribe#use-the-dapr-net-sdk