푸터 콘텐츠로 바로가기
.NET 도움말

NServiceBus C# (How It Works For Developers)

NServiceBus is a powerful and adaptable service bus designed for the .NET Framework that streamlines distributed system development. The strong messaging patterns it offers guarantee dependable message handling and delivery across several microservices and applications. NServiceBus abstracts the underlying messaging architecture, allowing developers to concentrate on business logic instead of the intricacies of building distributed systems.

In contrast, IronPDF is a well-liked .NET library for generating, viewing, and modifying PDF files. It is well-known for being easy to use and very efficient at creating PDFs from various sources, such as ASPX files and HTML.

Developers may build dependable, scalable, and maintainable software systems that can generate and manage PDF documents as part of their business operations by combining NServiceBus and IronPDF.

We will look at how to set up a simple C# NServiceBus project and integrate it with IronPDF in this article, so you can build a streamlined workflow for managing and producing PDF documents in a distributed application architecture. After reading this introduction tutorial, you ought to know exactly how these two effective technologies can cooperate to simplify your PDF-related tasks in a distributed setting.

What is NServiceBus C#?

NServiceBus is a powerful and adaptable framework that makes it easy to create distributed systems and service-oriented .NET architectures. By utilizing NServiceBus, you can easily manage various message types and ensure reliable communication. This is crucial, particularly in a web application and similar architectures where seamless message routing and processing are essential. NServiceBus's message handlers effectively deal with receiving messages, ensuring that every logical component interacts smoothly. NServiceBus has the following important features:

NServiceBus C# (How It Works For Developers): Figure 1 - NServiceBus C#

Features of NServiceBus

Message-Based Communication

NServiceBus encourages message-based communication between different services or components in a system. By decoupling components, this method creates designs that are easier to scale and manage.

Reliable Messaging

By automatically managing retries, dead-letter queues, and other fault tolerance techniques, it guarantees dependable message delivery. In distributed systems, where network outages and other problems of failure are frequent, this dependability is essential.

Publish/Subscribe Model

The publish/subscribe pattern is supported by NServiceBus, enabling services to publish events and let other services subscribe to these events. This makes event-driven architectures possible, in which modifications made to events in one component of the system can cause responses in other components.

Saga Management

Long-running business processes may be managed with NServiceBus thanks to its integrated support for sagas. Sagas make it possible for the service platform to manage state and coordinate intricate operations among several services.

Extensibility and Customization

It offers an exceptional level of extensibility, enabling developers to personalize the handling, processing, and transportation process of messages. Because of its adaptability, it can be used in a variety of scenarios.

Integration with Various Messaging Platforms

Numerous messaging systems, including MSMQ, RabbitMQ, Azure Service Bus, Amazon SQS, and others, can be integrated with NServiceBus. This enables developers to select the communications infrastructure solution that best suits their requirements.

Create and configure NServiceBus in C#

You must first set up your development environment, create a basic project, and build a basic messaging service and scenario before you can begin using NServiceBus in a C# project. Here's a step-by-step guide to get you going.

Create a New Visual Studio Project

In Visual Studio, the process of creating a console project is simple. Use these easy steps in the Visual Studio environment to launch a Console Application:

Make sure you have installed Visual Studio on your PC before using it.

Start a New Project

Click File, then select New, and finally Project.

NServiceBus C# (How It Works For Developers): Figure 2 - Click New

You can select the "Console App" or "Console App (.NET Core)" template from the list of project template references below.

Provide a name for your project in the "Name" field.

NServiceBus C# (How It Works For Developers): Figure 3 - Provide a name and location for the project

Choose a storage location for the project.

Clicking "Create" will start the Console application project.

NServiceBus C# (How It Works For Developers): Figure 4 - Click create

Install NServiceBus Packages

Navigate to Tools > NuGet Package Manager > Package Manager Console to open the NuGet Package Manager Console.

Run the following command to install the NServiceBus NuGet package.

Install-Package NServiceBus

Choose a Transport

Transport is needed by NServiceBus to receive and send messages. We'll stick with the Learning Transport since it's easy to use and works well for testing and development.

Install the package for Learning Transport by executing.

Install-Package NServiceBus.RabbitMQ

Configure NServiceBus

Set Up the Endpoint

Set the NServiceBus endpoint configuration in your Program.cs file:

using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;

class Program
{
    static async Task Main()
    {
        Console.Title = "Sender";
        var endpointConfiguration = new EndpointConfiguration("SenderEndpoint");

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to send a message...");
        Console.ReadLine();

        // Send a message
        var message = new MyMessage
        {
            Content = "Hello, NServiceBus with RabbitMQ!"
        };
        await endpointInstance.Send("ReceiverEndpoint", message).ConfigureAwait(false);
        Console.WriteLine("Message sent. Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;

class Program
{
    static async Task Main()
    {
        Console.Title = "Sender";
        var endpointConfiguration = new EndpointConfiguration("SenderEndpoint");

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to send a message...");
        Console.ReadLine();

        // Send a message
        var message = new MyMessage
        {
            Content = "Hello, NServiceBus with RabbitMQ!"
        };
        await endpointInstance.Send("ReceiverEndpoint", message).ConfigureAwait(false);
        Console.WriteLine("Message sent. Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
$vbLabelText   $csharpLabel

NServiceBus C# (How It Works For Developers): Figure 5 - Example console output

Create a Message

To represent the message, add a new class.

public class MyMessage : IMessage
{
    public string Content { get; set; }
}
public class MyMessage : IMessage
{
    public string Content { get; set; }
}
$vbLabelText   $csharpLabel

Create a Message Handler

To handle the message, add a new class.

using NServiceBus;
using System.Threading.Tasks;

public class MyMessageHandler : IHandleMessages<MyMessage>
{
    public Task Handle(MyMessage message, IMessageHandlerContext context)
    {
        Console.WriteLine($"Received message: {message.Content}");
        return Task.CompletedTask;
    }
}
using NServiceBus;
using System.Threading.Tasks;

public class MyMessageHandler : IHandleMessages<MyMessage>
{
    public Task Handle(MyMessage message, IMessageHandlerContext context)
    {
        Console.WriteLine($"Received message: {message.Content}");
        return Task.CompletedTask;
    }
}
$vbLabelText   $csharpLabel

Sending a Message

Send a Message from the Endpoint. Adapt your primary way to transmit a message with the help of the handler.

using NServiceBus;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.Title = "Receiver";
        var endpointConfiguration = new EndpointConfiguration("ReceiverEndpoint");

        // Serialization configuration
        endpointConfiguration.UseSerialization<NewtonsoftJsonSerializer>();

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.UseConventionalRoutingTopology(QueueType.Quorum);
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        endpointConfiguration.EnableInstallers();

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
using NServiceBus;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.Title = "Receiver";
        var endpointConfiguration = new EndpointConfiguration("ReceiverEndpoint");

        // Serialization configuration
        endpointConfiguration.UseSerialization<NewtonsoftJsonSerializer>();

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.UseConventionalRoutingTopology(QueueType.Quorum);
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        endpointConfiguration.EnableInstallers();

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
$vbLabelText   $csharpLabel

NServiceBus C# (How It Works For Developers): Figure 6 - Example console output

Launch the application and build the project. The console should display the message "Received message: Hello, NServiceBus!"

Getting Started

In a C# project, integrating NServiceBus with RabbitMQ and IronPDF entails configuring messages between NServiceBus and RabbitMQ as well as using IronPDF to create PDFs. Here is a thorough how-to to get you going:

What is IronPDF?

IronPDF is a .NET library designed for creating, reading, editing, and converting PDF files. With it, programmers may work with PDF files in C# or VB.NET applications with a powerful and intuitive tool. The characteristics and capabilities of IronPDF are fully described below:

NServiceBus C# (How It Works For Developers): Figure 7 - IronPDF: The C# PDF Library homepage

Features of IronPDF

PDF Generation from HTML

Convert JavaScript, HTML, and CSS to PDF. Supports media queries and responsive design, two contemporary web standards. Useful for producing dynamically styled PDF documents, invoices, and reports using HTML and CSS.

PDF Editing

To already existing PDFs, add text, pictures, and other material. Take text and pictures out of PDF files. Combine several PDFs into one file. Divide PDF files into several documents. Include annotations, footers, headers, and watermarks.

PDF Conversion

Convert Word, Excel, image, and other file formats to PDF. PDF to image conversion (PNG, JPEG, etc.).

Performance and Reliability

High performance and dependability are the design goals in production settings. Efficiently manages huge documents.

Installation of IronPDF

Install IronPDF by opening the NuGet Package Manager Console.

Install-Package IronPdf

Configure the Sender With Message

Messages is a shared project (class library) that the sender and the recipient will both use. Define the message class in the Messages project. Create a new Class Library project called Messages and add it to the solution.

Define the Message:

Inside the Messages project, create a new class called GeneratePdfMessage.cs:

using NServiceBus;

public class GeneratePdfMessage : IMessage
{
    public string Content { get; set; }
    public string OutputPath { get; set; }
}
using NServiceBus;

public class GeneratePdfMessage : IMessage
{
    public string Content { get; set; }
    public string OutputPath { get; set; }
}
$vbLabelText   $csharpLabel

In both the Sender and Receiver projects, include a reference to the Messages project.

Set up the NServiceBus endpoint in the Sender project to use RabbitMQ for message delivery.

using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;

class Program
{
    static async Task Main()
    {
        Console.Title = "Sender";
        var endpointConfiguration = new EndpointConfiguration("SenderEndpoint");

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        endpointConfiguration.EnableInstallers();

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to send a message...");
        Console.ReadLine();

        // Send a message
        var message = new GeneratePdfMessage
        {
            Content = "<h1>Hello, NServiceBus with RabbitMQ and IronPDF!</h1>",
            OutputPath = "output.pdf"
        };
        await endpointInstance.Send("ReceiverEndpoint", message).ConfigureAwait(false);
        Console.WriteLine("Message sent. Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;

class Program
{
    static async Task Main()
    {
        Console.Title = "Sender";
        var endpointConfiguration = new EndpointConfiguration("SenderEndpoint");

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        endpointConfiguration.EnableInstallers();

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to send a message...");
        Console.ReadLine();

        // Send a message
        var message = new GeneratePdfMessage
        {
            Content = "<h1>Hello, NServiceBus with RabbitMQ and IronPDF!</h1>",
            OutputPath = "output.pdf"
        };
        await endpointInstance.Send("ReceiverEndpoint", message).ConfigureAwait(false);
        Console.WriteLine("Message sent. Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
$vbLabelText   $csharpLabel

Endpoint Configuration: the endpoint is initialized with the name "SenderEndpoint" by calling new EndpointConfiguration("SenderEndpoint").

endpointConfiguration is the transport configuration. By connecting to a local RabbitMQ instance, the method UseTransport() sets up NServiceBus to use RabbitMQ as the transport mechanism.

Audit and Error Queues Where to send failed messages and audit processed messages is configured using SendFailedMessagesTo("error") and AuditProcessedMessagesTo("audit"), respectively.

Message Sent: endpointInstance.Send("ReceiverEndpoint", message) sends a GeneratePdfMessage to the "ReceiverEndpoint".

Configure the Receiver to Generate PDF

Set up the NServiceBus endpoint in the Receiver project to accept messages over RabbitMQ and produce PDFs using IronPDF.

using NServiceBus;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.Title = "Receiver";
        var endpointConfiguration = new EndpointConfiguration("ReceiverEndpoint");

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
using NServiceBus;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.Title = "Receiver";
        var endpointConfiguration = new EndpointConfiguration("ReceiverEndpoint");

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
$vbLabelText   $csharpLabel

This setup, for the "ReceiverEndpoint" receiver endpoint, is comparable to the Sender configuration.

Message Handler

In the Receiver project, create a new class called GeneratePdfMessageHandler.cs.

using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;
using IronPdf;

public class GeneratePdfMessageHandler : IHandleMessages<GeneratePdfMessage>
{
    public Task Handle(GeneratePdfMessage message, IMessageHandlerContext context)
    {
        Console.WriteLine($"Received message to generate PDF with content: {message.Content}");

        // Generate PDF
        var renderer = new HtmlToPdf();
        var pdf = renderer.RenderHtmlAsPdf(message.Content);
        pdf.SaveAs(message.OutputPath);
        Console.WriteLine($"PDF generated and saved to: {message.OutputPath}");

        return Task.CompletedTask;
    }
}
using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;
using IronPdf;

public class GeneratePdfMessageHandler : IHandleMessages<GeneratePdfMessage>
{
    public Task Handle(GeneratePdfMessage message, IMessageHandlerContext context)
    {
        Console.WriteLine($"Received message to generate PDF with content: {message.Content}");

        // Generate PDF
        var renderer = new HtmlToPdf();
        var pdf = renderer.RenderHtmlAsPdf(message.Content);
        pdf.SaveAs(message.OutputPath);
        Console.WriteLine($"PDF generated and saved to: {message.OutputPath}");

        return Task.CompletedTask;
    }
}
$vbLabelText   $csharpLabel

GeneratePdfMessageHandler uses the IHandleMessages interface to handle messages of type GeneratePdfMessage.

NServiceBus C# (How It Works For Developers): Figure 8 - Example console output

Handle Method: After receiving the message, the Handle function creates a PDF using IronPDF. The HTML content in the message is converted into a PDF by the HtmlToPdf renderer code, which then saves it to the designated output path.

NServiceBus C# (How It Works For Developers): Figure 9 - PDF output from using NServiceBus with RabbitMQ along with IronPDF

Conclusion

NServiceBus may be integrated with RabbitMQ and IronPDF in C# to provide a scalable and stable solution for distributed systems that need to generate PDFs dynamically and reliably. This combination makes use of NServiceBus's message processing capabilities, RabbitMQ's dependability and adaptability as a message broker, and IronPDF's robust PDF editing tools. Decoupling between services is ensured by the resultant architecture, allowing for autonomous evolution and scalability.

RabbitMQ also ensures message delivery even in the event of network or application failures. NServiceBus makes message routing and processing simpler, and IronPDF makes it possible to convert HTML text into high-quality PDF documents. This integration offers a flexible framework for developing sophisticated, large-scale applications in addition to improving the maintainability and dependability of the system.

Lastly, by adding IronPDF and Iron Software to your toolkit for .NET programming, you can effectively work with barcodes, generate PDFs, perform OCR, and link with Excel. IronPDF’s Licensing Page, which starts at $799, seamlessly blends its features and the performance, compatibility, and ease of use of Iron Software’s Official Site's flexible suite to provide additional web applications and capabilities and more efficient development.

If there are well-defined license options that are customized to the specific requirements of the project, developers can select the optimal model with confidence. These benefits allow developers to handle a range of difficulties effectively and transparently.

자주 묻는 질문

분산 시스템 개발을 위해 C#에서 NServiceBus를 사용하려면 어떻게 해야 하나요?

NServiceBus는 메시징 아키텍처를 추상화하여 C#에서 분산 시스템 개발을 간소화합니다. 이를 통해 개발자는 마이크로서비스 전반에서 안정적인 메시지 처리 및 전달을 보장하면서 비즈니스 로직에 집중할 수 있습니다.

NServiceBus와 PDF 관리 라이브러리를 통합하면 어떤 이점이 있나요?

NServiceBus를 IronPDF와 같은 PDF 관리 라이브러리와 통합하면 분산된 애플리케이션 내에서 효율적인 PDF 생성 및 관리가 가능하므로 확장 가능하고 유지 관리가 가능한 소프트웨어 시스템을 구축할 수 있습니다.

NServiceBus 및 RabbitMQ로 C# 프로젝트를 어떻게 설정하나요?

NServiceBus 및 RabbitMQ를 사용하여 C# 프로젝트를 설정하려면 Visual Studio에서 새 콘솔 애플리케이션을 만들고, NServiceBus 및 RabbitMQ NuGet 패키지를 설치한 다음 코드에서 엔드포인트 및 메시징 전송을 구성합니다.

NServiceBus는 메시지 기반 커뮤니케이션을 어떻게 향상시키나요?

NServiceBus는 게시/구독 모델 및 사가 관리와 같은 안정적인 메시징 패턴을 제공하여 분산된 시스템에서 메시지가 올바르게 전달되고 처리되도록 함으로써 메시지 기반 커뮤니케이션을 향상시킵니다.

NServiceBus를 사용하는 분산 시스템에서 IronPDF는 어떤 역할을 하나요?

IronPDF는 문서 처리 프로세스를 자동화하기 위해 메시지 중심 워크플로우에 통합할 수 있는 강력한 PDF 생성 및 조작 기능을 제공함으로써 NServiceBus를 사용하는 분산 시스템에서 중요한 역할을 합니다.

C#을 사용하는 분산 시스템에서 안정적인 PDF 생성을 보장하려면 어떻게 해야 할까요?

C#을 사용하는 분산 시스템에서 안정적인 PDF 생성은 메시지 처리를 위한 NServiceBus와 PDF 생성을 위한 IronPDF를 통합하여 작업을 조정하고 일관성을 보장하는 RabbitMQ의 메시징 기능을 활용함으로써 달성할 수 있습니다.

NServiceBus에서 게시/구독 모델은 어떻게 작동하나요?

NServiceBus에서는 게시/구독 모델을 통해 서비스가 다른 서비스가 구독할 수 있는 이벤트를 게시할 수 있습니다. 이를 통해 한 구성 요소의 변경 사항이 다른 구성 요소의 작업을 트리거하여 시스템 응답성과 확장성을 개선할 수 있는 이벤트 중심 아키텍처를 구현할 수 있습니다.

NServiceBus에서 사가 관리의 중요성은 무엇인가요?

NServiceBus의 사가 관리는 여러 서비스에서 장기적으로 실행되는 비즈니스 프로세스를 조정하여 분산된 시스템 내에서 복잡한 워크플로가 정확하고 일관되게 실행되도록 하는 데 중요한 역할을 합니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.