-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathMessageBusBuilder.cs
361 lines (303 loc) · 13.5 KB
/
MessageBusBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
namespace SlimMessageBus.Host;
using Microsoft.Extensions.DependencyInjection.Extensions;
public class MessageBusBuilder : IHasPostConfigurationActions, ISerializationBuilder, IProducerBuilder
{
/// <summary>
/// Parent bus builder.
/// </summary>
public MessageBusBuilder Parent { get; private set; }
/// <summary>
/// Declared child buses.
/// </summary>
public IDictionary<string, MessageBusBuilder> Children { get; } = new Dictionary<string, MessageBusBuilder>();
/// <summary>
/// The current settings that are being built.
/// </summary>
public MessageBusSettings Settings { get; private set; } = new();
HasProviderExtensions IBuilderWithSettings.Settings => Settings;
/// <summary>
/// The bus factory method.
/// </summary>
public Func<MessageBusSettings, IMessageBusProvider> BusFactory { get; private set; }
public IList<Action<IServiceCollection>> PostConfigurationActions { get; } = [];
protected MessageBusBuilder()
{
}
protected MessageBusBuilder(MessageBusBuilder other)
{
Settings = other.Settings;
Children = other.Children;
BusFactory = other.BusFactory;
PostConfigurationActions = other.PostConfigurationActions;
}
public static MessageBusBuilder Create() => new();
public MessageBusBuilder MergeFrom(MessageBusSettings settings)
{
if (settings is null) throw new ArgumentNullException(nameof(settings));
Settings.MergeFrom(settings);
return this;
}
/// <summary>
/// Configures (declares) the production (publishing for pub/sub or request sending in request/response) of a message
/// </summary>
/// <typeparam name="T">Type of the message</typeparam>
/// <param name="builder"></param>
/// <returns></returns>
public MessageBusBuilder Produce<T>(Action<ProducerBuilder<T>> builder)
{
if (builder == null) throw new ArgumentNullException(nameof(builder));
var item = new ProducerSettings();
builder(new ProducerBuilder<T>(item));
Settings.Producers.Add(item);
return this;
}
/// <summary>
/// Configures (declares) the production (publishing for pub/sub or request sending in request/response) of a message
/// </summary>
/// <param name="messageType">Type of the message</param>
/// <param name="builder"></param>
/// <returns></returns>
public MessageBusBuilder Produce(Type messageType, Action<ProducerBuilder<object>> builder)
{
if (builder == null) throw new ArgumentNullException(nameof(builder));
var item = new ProducerSettings();
builder(new ProducerBuilder<object>(item, messageType));
Settings.Producers.Add(item);
return this;
}
/// <summary>
/// Configures (declares) the consumer of given message types in pub/sub or queue communication.
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <param name="builder"></param>
/// <returns></returns>
public MessageBusBuilder Consume<TMessage>(Action<ConsumerBuilder<TMessage>> builder)
{
if (builder == null) throw new ArgumentNullException(nameof(builder));
var b = new ConsumerBuilder<TMessage>(Settings);
builder(b);
if (b.ConsumerSettings.ConsumerType is null)
{
// Apply default consumer type of not set
b.WithConsumer<IConsumer<TMessage>>();
}
return this;
}
/// <summary>
/// Configures (declares) the consumer of given message types in pub/sub or queue communication.
/// </summary>
/// <param name="messageType">Type of message</param>
/// <param name="builder"></param>
/// <returns></returns>
public MessageBusBuilder Consume(Type messageType, Action<ConsumerBuilder<object>> builder)
{
if (builder == null) throw new ArgumentNullException(nameof(builder));
builder(new ConsumerBuilder<object>(Settings, messageType));
return this;
}
/// <summary>
/// Configures (declares) the handler of a given request message type in request-response communication.
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
/// <param name="builder"></param>
/// <returns></returns>
public MessageBusBuilder Handle<TRequest, TResponse>(Action<HandlerBuilder<TRequest, TResponse>> builder)
{
if (builder == null) throw new ArgumentNullException(nameof(builder));
var b = new HandlerBuilder<TRequest, TResponse>(Settings);
builder(b);
if (b.ConsumerSettings.ConsumerType is null)
{
// Apply default handler type of not set
b.WithHandler<IRequestHandler<TRequest, TResponse>>();
}
return this;
}
/// <summary>
/// Configures (declares) the handler of a given request message type which has no response message type.
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <param name="builder"></param>
/// <returns></returns>
public MessageBusBuilder Handle<TRequest>(Action<HandlerBuilder<TRequest>> builder)
{
if (builder == null) throw new ArgumentNullException(nameof(builder));
var b = new HandlerBuilder<TRequest>(Settings);
builder(b);
if (b.ConsumerSettings.ConsumerType is null)
{
// Apply default handler type of not set
b.WithHandler<IRequestHandler<TRequest>>();
}
return this;
}
/// <summary>
/// Configures (declares) the handler of a given request message type in request-response communication.
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
/// <param name="builder"></param>
/// <returns></returns>
public MessageBusBuilder Handle(Type requestType, Type responseType, Action<HandlerBuilder<object, object>> builder)
{
if (requestType == null) throw new ArgumentNullException(nameof(requestType));
if (responseType == null) throw new ArgumentNullException(nameof(responseType));
if (builder == null) throw new ArgumentNullException(nameof(builder));
builder(new HandlerBuilder<object, object>(Settings, requestType, responseType));
return this;
}
/// <summary>
/// Configures (declares) the handler of a given request message type (for which there is no response type) in request-response communication.
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
/// <param name="builder"></param>
/// <returns></returns>
public MessageBusBuilder Handle(Type requestType, Action<HandlerBuilder<object>> builder)
{
if (requestType == null) throw new ArgumentNullException(nameof(requestType));
if (builder == null) throw new ArgumentNullException(nameof(builder));
builder(new HandlerBuilder<object>(Settings, requestType));
return this;
}
public MessageBusBuilder ExpectRequestResponses(Action<RequestResponseBuilder> reqRespBuilder)
{
if (reqRespBuilder == null) throw new ArgumentNullException(nameof(reqRespBuilder));
var item = new RequestResponseSettings();
reqRespBuilder(new RequestResponseBuilder(item));
Settings.RequestResponse = item;
return this;
}
/// <summary>
/// Serializer type (<see cref="IMessageSerializer"/>) to look up in the DI for this bus.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public MessageBusBuilder WithSerializer<T>() where T : IMessageSerializer => WithSerializer(typeof(T));
/// <summary>
/// Serializer type (<see cref="IMessageSerializer"/>) to look up in the DI for this bus.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public MessageBusBuilder WithSerializer(Type serializerType)
{
if (serializerType is not null && !typeof(IMessageSerializer).IsAssignableFrom(serializerType))
{
throw new ConfigurationMessageBusException($"The serializer type {serializerType.FullName} does not implement the interface {nameof(IMessageSerializer)}");
}
Settings.SerializerType = serializerType ?? throw new ArgumentNullException(nameof(serializerType));
return this;
}
public void RegisterSerializer<TMessageSerializer>(Action<IServiceCollection> services)
where TMessageSerializer : class, IMessageSerializer
{
PostConfigurationActions.Add(services);
PostConfigurationActions.Add(services => services.TryAddSingleton<IMessageSerializer>(sp => sp.GetRequiredService<TMessageSerializer>()));
}
public MessageBusBuilder WithDependencyResolver(IServiceProvider serviceProvider)
{
Settings.ServiceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
return this;
}
public MessageBusBuilder WithProvider(Func<MessageBusSettings, IMessageBusProvider> provider)
{
BusFactory = provider ?? throw new ArgumentNullException(nameof(provider));
return this;
}
public MessageBusBuilder Do(Action<MessageBusBuilder> builder)
{
if (builder == null) throw new ArgumentNullException(nameof(builder));
builder(this);
return this;
}
/// <summary>
/// Sets the default enable (or disable) creation of DI child scope for each message.
/// </summary>
/// <param name="enabled"></param>
/// <returns></returns>
public MessageBusBuilder PerMessageScopeEnabled(bool enabled = true)
{
Settings.IsMessageScopeEnabled = enabled;
return this;
}
public MessageBusBuilder WithMessageTypeResolver(Type messageTypeResolverType)
{
Settings.MessageTypeResolverType = messageTypeResolverType ?? throw new ArgumentNullException(nameof(messageTypeResolverType));
return this;
}
public MessageBusBuilder WithMessageTypeResolver<T>() => WithMessageTypeResolver(typeof(T));
/// <summary>
/// Hook called whenever message is being produced. Can be used to change message headers.
/// </summary>
/// <param name="executePrevious">Should the previously set modifier be executed as well?</param>
public MessageBusBuilder WithHeaderModifier(MessageHeaderModifier<object> headerModifier, bool executePrevious = true)
{
if (headerModifier == null) throw new ArgumentNullException(nameof(headerModifier));
var previousHeaderModifier = executePrevious ? Settings.HeaderModifier : null;
Settings.HeaderModifier = previousHeaderModifier == null
? headerModifier
: (headers, message) =>
{
previousHeaderModifier(headers, message);
headerModifier(headers, message);
};
return this;
}
/// <summary>
/// Hook called whenever message is being produced. Can be used to change message headers.
/// </summary>
/// <param name="executePrevious">Should the previously set modifier be executed as well?</param>
public MessageBusBuilder WithHeaderModifier<T>(MessageHeaderModifier<T> headerModifier, bool executePrevious = true)
=> WithHeaderModifier((headers, message) =>
{
if (message is T typedMessage)
{
headerModifier(headers, typedMessage);
}
},
executePrevious);
/// <summary>
/// Enables or disabled the auto start of message consumption upon bus creation. If false, then you need to call the .Start() on the bus to start consuming messages.
/// </summary>
/// <param name="enabled"></param>
public MessageBusBuilder AutoStartConsumersEnabled(bool enabled)
{
Settings.AutoStartConsumers = enabled;
return this;
}
/// <summary>
/// Adds a child bus with the given name <paramref name="busName"/>.
/// If the child bus with the given name already exists, it will be reused and only the <paramref name="builderAction"/> will be invoked to configure it.
/// </summary>
/// <param name="busName"></param>
/// <param name="builderAction"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public MessageBusBuilder AddChildBus(string busName, Action<MessageBusBuilder> builderAction)
{
if (busName is null) throw new ArgumentNullException(nameof(busName));
if (!Children.TryGetValue(busName, out var child))
{
child = Create();
child.Settings = new MessageBusSettings(Settings)
{
Name = busName
};
child.Parent = this;
Children.Add(busName, child);
child.MergeFrom(Settings);
}
builderAction?.Invoke(child);
return this;
}
public IMessageBusProvider Build()
{
if (BusFactory is null)
{
var busName = Settings.Name != null ? $"Child bus [{Settings.Name}]: " : string.Empty;
throw new ConfigurationMessageBusException($"{busName}The bus provider was not configured. Check the MessageBus configuration and ensure the has the '.WithProviderXxx()' setting for one of the available transports.");
}
return BusFactory(Settings);
}
}