RCommon
HomeGitHub
  • Introduction
  • Common Scenarios
  • Getting Started
    • Running Examples
    • Roadmap
    • Releases
      • 1.0.1.75
      • 1.0.2.0
      • 2.0.0
      • 2.1.0
  • Topics
    • Fundamentals
      • Configuration
      • Logging
      • GUID Generation
      • Time and Date
      • Emailing
        • SMTP Email
        • SendGrid Email API
      • Data Transfer Objects
        • Pagination
      • Security
        • Current User
        • Claims
      • Events
        • Transactional Events
        • Synchronous Events
        • Asynchronous Events
        • Producers
        • Subscribers
      • Validation
        • Fluent Validation
      • Caching
        • Dynamically Compiled Expressions
        • Persistence Caching
        • Caching Services
        • Redis & Valkey
        • Memory Cache
      • Serialization
        • JSON.NET
        • System.Text.Json
    • Patterns
      • Specification
      • Mediator
        • MediatR
          • Validator Behavior
          • Unit of Work Behavior
          • Logging Behavior
      • CQRS
        • Commands
        • Queries
      • Persistence
        • Repository
          • Entity Framework Core
          • Dapper
          • Linq2Db
        • Transactions
          • Unit of Work
      • Event Bus
        • In Memory
        • MediatR
        • Wolverine
      • Message Bus
        • MassTransit
        • Wolverine
    • Architecture
      • Overview
      • Microservices
      • Clean Architecture
      • Event Driven Architecture
  • Examples
    • Clean Architecture
    • CQRS
    • Mediator: MediatR
    • Event Handling: In Memory
    • Event Handling: MediatR
    • Event Handling: MassTransit
    • Event Handling: Wolverine
    • Validation: Fluent Validation
Powered by GitBook
On this page
  • Overview
  • Configuration
  • Implementation
  1. Topics
  2. Patterns
  3. Message Bus

MassTransit

MassTransit message bus event handling implementation in RCommon

PreviousMessage BusNextWolverine

Last updated 9 months ago

Overview

is a framework that abstracts away the complexities of messaging queues and distributed computing at large. It is perhaps one of the best message bus implementations in the .NET ecosystem and is incredibly feature rich.

and well supported by the open source community.

Configuration

using Examples.Messaging.MassTransit;
using MassTransit;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using RCommon;
using RCommon.EventHandling;
using RCommon.EventHandling.Producers;
using RCommon.MassTransit;
using RCommon.MassTransit.Producers;
using System.Diagnostics;

try
{
    var host = Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((context, builder) =>
                {

                    ConfigurationContainer.Configuration = builder
                        .Build();
                })
                .ConfigureServices(services =>
                {
                    // Configure RCommon
                    services.AddRCommon()
                        .WithEventHandling<MassTransitEventHandlingBuilder>(eventHandling =>
                        {
                            // This is a wrapper for MassTransit configuration
                            eventHandling.UsingInMemory((context, cfg) =>
                            {
                                cfg.ConfigureEndpoints(context);
                            });

                            // A simple and consistent interface for adding producers and subscribers
                            eventHandling.AddProducer<PublishWithMassTransitEventProducer>();
                            eventHandling.AddSubscriber<TestEvent, TestEventHandler>();
                        });
                    services.AddHostedService<Worker>();
                }).Build();




    await host.RunAsync();
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());

}

Implementation

The implementation details for how you produce and subscribe to events will not change due to a consistent producer/subscriber API in RCommon.

Producing the Event

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        Console.WriteLine("Example Starting");
        var eventProducers = _serviceProvider.GetServices<IEventProducer>();
        var testEvent = new TestEvent(DateTime.Now, Guid.NewGuid());

        foreach (var producer in eventProducers)
        {
            Console.WriteLine($"Producer: {producer}");
            await producer.ProduceEventAsync(testEvent);
        }
        await Task.Delay(5000, stoppingToken);
        
    }
}

Subscribing to the Event

using RCommon.EventHandling.Subscribers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Examples.Messaging.MassTransit
{
    public class TestEventHandler : ISubscriber<TestEvent>
    {
        public TestEventHandler()
        {
                
        }
        
        public async Task HandleAsync(TestEvent notification, CancellationToken cancellationToken = default)
        {
            Console.WriteLine("I just handled this event {0}", new object[] { notification.ToString() });
            Console.WriteLine("Example Complete");
            await Task.CompletedTask;
        }
    }
}

Try running some examples

MassTransit
MassTransit is very well documented
Event Handling: MassTransit