Milvasoft.Messaging 1.0.3

There is a newer version of this package available.
See the version list below for details.
dotnet add package Milvasoft.Messaging --version 1.0.3                
NuGet\Install-Package Milvasoft.Messaging -Version 1.0.3                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Milvasoft.Messaging" Version="1.0.3" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Milvasoft.Messaging --version 1.0.3                
#r "nuget: Milvasoft.Messaging, 1.0.3"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Milvasoft.Messaging as a Cake Addin
#addin nuget:?package=Milvasoft.Messaging&version=1.0.3

// Install Milvasoft.Messaging as a Cake Tool
#tool nuget:?package=Milvasoft.Messaging&version=1.0.3                

Provides models and configurations for message broker and service bus operations. With MassTransit

license NuGet NuGet

Requirements

One of the runtime environment is required from below

  • .NET 5.0
  • RabbitMQ

Installation

For now you'll need to install following libraries:

  • To install Milvasoft.Messaging, run the following command in the Package Manager Console
Install-Package Milvasoft.Messaging

Or you can download the latest .dll from Github

Before using this library install RabbitMQ to your machine. You can run RabbitMQ easily with Docker.

Milvasoft.Messaging Usage

In Startup.cs;


...
	    
 services.AddMilvaMessaging(cfg =>
 {
     cfg.RabbitMqUri = "rabbitmq://localhost:5672/";
     cfg.UserName = "admin";
     cfg.Password = "yourstrongpassword";
 });

...

For send mail command to RabbitMQ, you can use ready made publisher;


...

var commandSender = (ICommandSender)httpContext.RequestServices.GetService(typeof(ICommandSender));	  
  
await _lazyCommandSender.Value.PublishSendMailCommandAsync(new SendMailCommand
{
    From = "sender@yourdomain.com",
    FromPassword = "yourstrongpassword",
    Port = 587,
    SmtpHost = "mail.yourdomain.com",
    To = "reciever@somedomain.com",
    Subject = "Test Mail",
    HtmlBody = htmlContent
});

...

Or you can publish command manually.

For recieve and process send mail, you must write consumer project. This can be console application, web api or etc. We will create console application for this tutorial.

The console project you have created needs to be constantly up, so that it listens to the RabbitMQ queue and performs the operation when a new command arrives. For this, your main method must be as follows in Program.cs;


static async Task Main(string[] args)
{
    Console.Title = "Milvasoft.MailSenderMicroService";

    var builder = new HostBuilder().ConfigureServices((hostContext, services) =>
    {
        services.AddHostedService<MailHostedService>();

        var busConfigurator = new RabbitMqBusConfigurator(new RabbitMqConfiguration
        {
            RabbitMqUri = "rabbitmq://localhost:5672/",
            UserName = "admin",
            Password = "yourstrongpassword",
        });

        var bus = busConfigurator.CreateBus(cfg =>
        {            
            cfg.ReceiveEndpoint(RabbitMqConstants.MailServiceQueueName, e =>
            {
                e.Consumer<SendMailCommandConsumer>();
                
                //You can configure your recieve endpoint according to your needs in MassTransit.
                e.UseMessageRetry(r => r.Interval(2, 30000));
                e.UseRateLimit(30, TimeSpan.FromMinutes(1));
            });
        });

        services.AddSingleton(bus);
    });

    await builder.RunConsoleAsync();
}

Create new class which named MailHostedService. This will provide your console app is constantly up.


using MassTransit;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Milvasoft.Consumers.Mails
{
    public class MailHostedService : IHostedService
    {
        private readonly IBusControl _bus;

        /// <summary>
        /// Initializes new instance of <see cref="MailHostedService"/>.
        /// </summary>
        /// <param name="bus"></param>
        public MailHostedService(IBusControl bus)
        {
            _bus = bus;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await Console.Out.WriteLineAsync("Listening for Email Service commands/events...");

            await _bus.StartAsync(cancellationToken).ConfigureAwait(false);
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("Email Service stopping.");

            return _bus.StopAsync(cancellationToken);
        }
    }
}

Create class which named SendMailCommandConsumer. This class will run the incoming commands when a new command arrives in the listening queue.


using MassTransit;
using Milvasoft.Messaging.RabbitMq.Commands;
using System;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;

namespace Milvasoft.Consumers.Mails
{
    public class SendMailCommandConsumer : IConsumer<ISendMailCommand>
    {
        public async Task Consume(ConsumeContext<ISendMailCommand> context)
        {
            try
            {
                using var mailMessage = new MailMessage(context.Message.From,
                                                        context.Message.To,
                                                        context.Message.Subject,
                                                        context.Message.HtmlBody)
                {
                    IsBodyHtml = true
                };

                using var smtpClient = new SmtpClient(context.Message.SmtpHost, context.Message.Port);

                smtpClient.Credentials = new NetworkCredential(context.Message.From, context.Message.FromPassword);

                await smtpClient.SendMailAsync(mailMessage).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await Console.Out.WriteLineAsync("An error occured when sending mail.");
            }
        }
    }
}

In this way, you can perform operations independent of your project with RabbitMQ. The main purpose of the library is to combine the models that need to be shared between the publisher and the consumer projects and to provide an abstraction for doing these operations.

You can contribute to the improve of this library by adding more various operations like mail sending.

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
8.0.0 240 11/20/2023
7.0.0 159 5/7/2023
6.0.3 1,055 11/29/2021
6.0.2 1,535 11/28/2021
6.0.1 391 11/13/2021
6.0.0 311 11/10/2021
1.0.4 324 11/9/2021
1.0.3 416 10/30/2021
1.0.2 368 10/30/2021
1.0.1 381 10/11/2021
1.0.0 388 10/11/2021