├── .gitignore
├── GettingStarted
├── appsettings.json
├── appsettings.Development.json
├── Properties
│ └── launchSettings.json
├── GettingStarted.csproj
├── MessageConsumer.cs
├── Worker.cs
└── Program.cs
├── GettingStarted.sln
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | *.suo
2 | *.user
3 | bin
4 | obj
5 |
6 | .DS_Store
7 | *.DotSettings
8 |
9 | **/.vs
10 | **/.vscode
11 | **/.idea
12 |
--------------------------------------------------------------------------------
/GettingStarted/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/GettingStarted/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/GettingStarted/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "profiles": {
3 | "GettingStarted": {
4 | "commandName": "Project",
5 | "dotnetRunMessages": "true",
6 | "environmentVariables": {
7 | "DOTNET_ENVIRONMENT": "Development"
8 | }
9 | }
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/GettingStarted/GettingStarted.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 | dotnet-GettingStarted-3E162B96-73F8-4A27-B944-554C241030D4
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/GettingStarted/MessageConsumer.cs:
--------------------------------------------------------------------------------
1 | using System.Threading.Tasks;
2 | using MassTransit;
3 | using Microsoft.Extensions.Logging;
4 |
5 | namespace GettingStarted
6 | {
7 | public class Message
8 | {
9 | public string Text { get; set; }
10 | }
11 |
12 | public class MessageConsumer :
13 | IConsumer
14 | {
15 | readonly ILogger _logger;
16 |
17 | public MessageConsumer(ILogger logger)
18 | {
19 | _logger = logger;
20 | }
21 |
22 | public Task Consume(ConsumeContext context)
23 | {
24 | _logger.LogInformation("Received Text: {Text}", context.Message.Text);
25 |
26 | return Task.CompletedTask;
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/GettingStarted/Worker.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Threading;
3 | using System.Threading.Tasks;
4 | using MassTransit;
5 | using Microsoft.Extensions.Hosting;
6 |
7 | namespace GettingStarted
8 | {
9 | public class Worker : BackgroundService
10 | {
11 | readonly IBus _bus;
12 |
13 | public Worker(IBus bus)
14 | {
15 | _bus = bus;
16 | }
17 |
18 | protected override async Task ExecuteAsync(CancellationToken stoppingToken)
19 | {
20 | while (!stoppingToken.IsCancellationRequested)
21 | {
22 | await _bus.Publish(new Message { Text = $"The time is {DateTimeOffset.Now}" }, stoppingToken);
23 |
24 | await Task.Delay(1000, stoppingToken);
25 | }
26 | }
27 | }
28 | }
--------------------------------------------------------------------------------
/GettingStarted/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.DependencyInjection;
2 | using Microsoft.Extensions.Hosting;
3 | using MassTransit;
4 |
5 | namespace GettingStarted
6 | {
7 | public class Program
8 | {
9 | public static void Main(string[] args)
10 | {
11 | CreateHostBuilder(args).Build().Run();
12 | }
13 |
14 | public static IHostBuilder CreateHostBuilder(string[] args) =>
15 | Host.CreateDefaultBuilder(args)
16 | .ConfigureServices((hostContext, services) =>
17 | {
18 | services.AddMassTransit(x =>
19 | {
20 | x.AddConsumer();
21 |
22 | x.UsingRabbitMq((context,cfg) =>
23 | {
24 | cfg.ConfigureEndpoints(context);
25 | });
26 | });
27 |
28 | services.AddHostedService();
29 | });
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/GettingStarted.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.26124.0
5 | MinimumVisualStudioVersion = 15.0.26124.0
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GettingStarted", "GettingStarted\GettingStarted.csproj", "{9CF94616-6CD1-41E1-9666-E3CE592F9D88}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Debug|x64 = Debug|x64
12 | Debug|x86 = Debug|x86
13 | Release|Any CPU = Release|Any CPU
14 | Release|x64 = Release|x64
15 | Release|x86 = Release|x86
16 | EndGlobalSection
17 | GlobalSection(SolutionProperties) = preSolution
18 | HideSolutionNode = FALSE
19 | EndGlobalSection
20 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
21 | {9CF94616-6CD1-41E1-9666-E3CE592F9D88}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
22 | {9CF94616-6CD1-41E1-9666-E3CE592F9D88}.Debug|Any CPU.Build.0 = Debug|Any CPU
23 | {9CF94616-6CD1-41E1-9666-E3CE592F9D88}.Debug|x64.ActiveCfg = Debug|Any CPU
24 | {9CF94616-6CD1-41E1-9666-E3CE592F9D88}.Debug|x64.Build.0 = Debug|Any CPU
25 | {9CF94616-6CD1-41E1-9666-E3CE592F9D88}.Debug|x86.ActiveCfg = Debug|Any CPU
26 | {9CF94616-6CD1-41E1-9666-E3CE592F9D88}.Debug|x86.Build.0 = Debug|Any CPU
27 | {9CF94616-6CD1-41E1-9666-E3CE592F9D88}.Release|Any CPU.ActiveCfg = Release|Any CPU
28 | {9CF94616-6CD1-41E1-9666-E3CE592F9D88}.Release|Any CPU.Build.0 = Release|Any CPU
29 | {9CF94616-6CD1-41E1-9666-E3CE592F9D88}.Release|x64.ActiveCfg = Release|Any CPU
30 | {9CF94616-6CD1-41E1-9666-E3CE592F9D88}.Release|x64.Build.0 = Release|Any CPU
31 | {9CF94616-6CD1-41E1-9666-E3CE592F9D88}.Release|x86.ActiveCfg = Release|Any CPU
32 | {9CF94616-6CD1-41E1-9666-E3CE592F9D88}.Release|x86.Build.0 = Release|Any CPU
33 | EndGlobalSection
34 | EndGlobal
35 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Getting Started with MassTransit
2 |
3 | This project is [part of the MassTransit documentation](https://masstransit-project.com/getting-started/). Refer to that link for details.
4 |
5 | Getting started with MassTransit is fast and easy. This quick start guide uses RabbitMQ with .NET 5. RabbitMQ must be installed, instructions for installing RabbitMQ are included [below](#install-rabbitmq).
6 |
7 | > The [.NET 5 SDK](https://dotnet.microsoft.com/download) should be installed before continuing.
8 |
9 | To create a service using MassTransit, create a worker via the Command Prompt.
10 |
11 | ```bash
12 | $ mkdir GettingStarted
13 | $ dotnet new worker -n GettingStarted
14 | ```
15 |
16 | ## Using the InMemory Transport
17 |
18 | Add MassTransit package to the console application:
19 |
20 | ```bash
21 | $ cd GettingStarted
22 | $ dotnet add package MassTransit.AspNetCore
23 | ```
24 |
25 | At this point, the project should compile, but there is more work to be done. You can verify the project builds by executing:
26 |
27 | ```bash
28 | $ dotnet run
29 | ```
30 |
31 | You should see something similar to the output below (press Control+C to exit).
32 |
33 | ```
34 | Building...
35 | info: GettingStarted.Worker[0]
36 | Worker running at: 03/24/2021 11:38:29 -05:00
37 | info: Microsoft.Hosting.Lifetime[0]
38 | Application started. Press Ctrl+C to shut down.
39 | info: Microsoft.Hosting.Lifetime[0]
40 | Hosting environment: Development
41 | info: Microsoft.Hosting.Lifetime[0]
42 | Content root path: /Users/chris/Garbage/start/GettingStarted
43 | info: GettingStarted.Worker[0]
44 | Worker running at: 03/24/2021 11:38:30 -05:00
45 | ```
46 |
47 | ### Edit Program.cs
48 |
49 | ```csharp
50 | using MassTransit;
51 | ```
52 |
53 | ```csharp {5-14}
54 | public static IHostBuilder CreateHostBuilder(string[] args) =>
55 | Host.CreateDefaultBuilder(args)
56 | .ConfigureServices((hostContext, services) =>
57 | {
58 | services.AddMassTransit(x =>
59 | {
60 | x.AddConsumer();
61 |
62 | x.UsingInMemory((context,cfg) =>
63 | {
64 | cfg.ConfigureEndpoints(context);
65 | });
66 | });
67 | services.AddMassTransitHostedService(true);
68 |
69 | services.AddHostedService();
70 | });
71 | ```
72 |
73 | ### Add a Consumer
74 |
75 | Create a new class file `MessageConsumer.cs` in the project:
76 |
77 | ```csharp
78 | using System.Threading.Tasks;
79 | using MassTransit;
80 | using Microsoft.Extensions.Logging;
81 |
82 | namespace GettingStarted
83 | {
84 | public class Message
85 | {
86 | public string Text { get; set; }
87 | }
88 |
89 | public class MessageConsumer :
90 | IConsumer
91 | {
92 | readonly ILogger _logger;
93 |
94 | public MessageConsumer(ILogger logger)
95 | {
96 | _logger = logger;
97 | }
98 |
99 | public Task Consume(ConsumeContext context)
100 | {
101 | _logger.LogInformation("Received Text: {Text}", context.Message.Text);
102 |
103 | return Task.CompletedTask;
104 | }
105 | }
106 | }
107 | ```
108 |
109 | ### Update the Worker
110 |
111 | ```csharp
112 | public class Worker : BackgroundService
113 | {
114 | readonly IBus _bus;
115 |
116 | public Worker(IBus bus)
117 | {
118 | _bus = bus;
119 | }
120 |
121 | protected override async Task ExecuteAsync(CancellationToken stoppingToken)
122 | {
123 | while (!stoppingToken.IsCancellationRequested)
124 | {
125 | await _bus.Publish(new Message {Text = $"The time is {DateTimeOffset.Now}"});
126 |
127 | await Task.Delay(1000, stoppingToken);
128 | }
129 | }
130 | }
131 | ```
132 |
133 | ### Run the project
134 |
135 | ```bash
136 | $ dotnet run
137 | ```
138 |
139 | The output should have changed to show the message consumer generating the output (again, press Control+C to exit).
140 |
141 | ``` {2-5,12-15}
142 | Building...
143 | info: MassTransit[0]
144 | Configured endpoint Message, Consumer: GettingStarted.MessageConsumer
145 | info: MassTransit[0]
146 | Bus started: loopback://localhost/
147 | info: Microsoft.Hosting.Lifetime[0]
148 | Application started. Press Ctrl+C to shut down.
149 | info: Microsoft.Hosting.Lifetime[0]
150 | Hosting environment: Development
151 | info: Microsoft.Hosting.Lifetime[0]
152 | Content root path: /Users/chris/Garbage/start/GettingStarted
153 | info: GettingStarted.MessageConsumer[0]
154 | Received Text: The time is 3/24/2021 12:02:01 PM -05:00
155 | info: GettingStarted.MessageConsumer[0]
156 | Received Text: The time is 3/24/2021 12:02:02 PM -05:00
157 | ```
158 |
159 | At this point, the consumer is configured on the bus and messages are published to the consumer.
160 |
161 | ## With RabbitMQ
162 |
163 | > See the [Install RabbitMQ](#install-rabbitmq) section below if you need to install RabbitMQ before continuing.
164 |
165 | Add RabbitMQ for MassTransit package to the console application.
166 |
167 | ```bash
168 | $ dotnet add package MassTransit.RabbitMQ
169 | ```
170 |
171 | ### Edit Program.cs
172 |
173 | Change `UsingInMemory` to `UsingRabbitMq`.
174 |
175 | ```csharp {9}
176 | public static IHostBuilder CreateHostBuilder(string[] args) =>
177 | Host.CreateDefaultBuilder(args)
178 | .ConfigureServices((hostContext, services) =>
179 | {
180 | services.AddMassTransit(x =>
181 | {
182 | x.AddConsumer();
183 |
184 | x.UsingRabbitMq((context,cfg) =>
185 | {
186 | cfg.ConfigureEndpoints(context);
187 | });
188 | });
189 |
190 | services.AddHostedService();
191 | });
192 | ```
193 |
194 | ### Run the project
195 |
196 | ```bash
197 | $ dotnet run
198 | ```
199 |
200 | The output should have changed to show the message consumer generating the output (again, press Control+C to exit). Notice that the bus address now starts with `rabbitmq`.
201 |
202 | ``` {11}
203 | Building...
204 | info: MassTransit[0]
205 | Configured endpoint Message, Consumer: GettingStarted.MessageConsumer
206 | info: Microsoft.Hosting.Lifetime[0]
207 | Application started. Press Ctrl+C to shut down.
208 | info: Microsoft.Hosting.Lifetime[0]
209 | Hosting environment: Development
210 | info: Microsoft.Hosting.Lifetime[0]
211 | Content root path: /Users/chris/Garbage/start/GettingStarted
212 | info: MassTransit[0]
213 | Bus started: rabbitmq://localhost/
214 | info: GettingStarted.MessageConsumer[0]
215 | Received Text: The time is 3/24/2021 12:11:10 PM -05:00
216 | ```
217 |
218 | At this point, the service is connecting to RabbbitMQ on `localhost`, and publishing messages which are received by the consumer.
219 |
220 | ### Install RabbitMQ
221 |
222 | RabbitMQ can be installed several different ways, depending upon your operating system and installed software.
223 |
224 | #### Docker
225 |
226 | The easiest by far is using Docker, which can be started as shown below. This will download and run a preconfigured Docker image, maintained by MassTransit, including the delayed exchange plug-in, as well as the Management interface enabled.
227 |
228 | ```bash
229 | $ docker run -p 15672:15672 -p 5672:5672 masstransit/rabbitmq
230 | ```
231 |
232 | #### Homebrew (Mac OS X)
233 |
234 | If you are using a Mac, RabbitMQ can be installed using [Homebrew](https://brew.sh/) by typing `brew install rabbitmq`. This installs the management plug-in automatically. Once installed, type `brew services start rabbitmq` and accept the prompts to enable network ports.
235 |
236 | #### To install RabbitMQ manually:
237 |
238 | 1. **Install Erlang** using the [installer](http://www.erlang.org/download.html). (Next -> Next ...)
239 | 2. **Install RabbitMQ** using the [installer](http://www.rabbitmq.com/download.html). (Next -> Next ...) You now have a RabbitMQ broker (look in `services.msc` for it) that you can [log into](http://localhost:15672/#/) using `guest`, `guest`. You can see message rates, routings and active consumers using this interface.
240 |
241 | ##### You need to add the management interface before you can login.
242 |
243 | 1. First, from an elevated command prompt, change directory to the sbin folder within the RabbitMQ Server installation directory e.g. `%PROGRAMFILES%\RabbitMQ Server\rabbitmq_server_3.5.3\sbin\`
244 |
245 | 2. Next, run the following command to enable the rabbitmq management plugin: `rabbitmq-plugins enable rabbitmq_management`
246 |
247 | ### What is this doing?
248 |
249 | If we are going to create a messaging system, we need to create a message. `Message` is a .NET class that will represent our message. Notice that it's just a Plain Old CLR Object (or POCO).
250 |
251 | Next up, the `AddMassTransit` extension is used to configure the bus in the container. The `UsingInMemory` (and `UsingRabbitMq`) method specifies the transport to use for the bus. Each transport has its own `UsingXxx` method.
252 |
253 | The consumer is added, using `AddConsumer`. This adds the consumer to the container as scoped.
254 |
255 | The `ConfigureEndpoints` method is used to automatically configure the receive endpoints on the bus. In this case, a single receive endpoint will be created for the `MessageConsumer`.
256 |
257 | The `AddMassTransitHostedService(true)` adds a hosted service for MassTransit that is responsible for starting and stopping the bus. This is required, as the bus will not operate propertly if it is not started and stopped.
258 |
259 | > This hosted service should be configured _prior_ to any other hosted services that may use the bus.
260 |
261 | Lastly, the `Worker` is updated to publish a message every second to the bus, which is subsequently consumed by the consumer.
262 |
263 |
--------------------------------------------------------------------------------