Search code examples
c#asp.net-core-3.1subscribenats.ionats-jetstream

NATS JetStream subscription in ASP.Net Core


I am subscribing to a NATS Jetstream channel and process the messages received from NATS Server. I can do it in a console app by connecting to NATS Server and subscribing to a subject. Now I am trying to configure the subscription in ASP.Net core app, so that it will always listen to the channel and process the messages it received. Could someone help me how and where to configure in ASP.Net core app?


Solution

  • You can implement and mount a hosted service to your core app. See docs

    Rough sample:

    public class NatsConsumerHostedService : IHostedService
    {
        private IAsyncSubscription? _subscription;
        
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            if (!cancellationToken.IsCancellationRequested)
            {
                // _subscription = await natsClient.Subscribe(...);
            }
        }
    
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await _subscription?.DrainAsync();
            _subscription?.Unsubscribe();
        }
    }
    

    Mounting it:

    var builder = WebApplication.CreateBuilder(args);
    // myriad of service registrations could go here...    
    builder.Services.AddHostedService<NatsConsumerHostedService>();