Microsoft.Extensions.DependencyInjection¶
This page demonstrates how ServiceBus.Core components can be registered using the Microsoft dependency injection container.
The examples focus on ServiceBus integration and do not attempt to document the Microsoft DI framework itself.
Install Package¶
dotnet add package Microsoft.Extensions.DependencyInjection
Register Formatter¶
Example:
services.AddSingleton<IDataFormatter>(
_ => new MsDataFormatter());
Register RabbitMQ Infrastructure¶
services.AddSingleton<IConnectionFactory>(
_ => new ConnectionFactory
{
HostName = "localhost"
});
services.AddSingleton<IConnection>(
provider =>
{
var factory =
provider.GetRequiredService<IConnectionFactory>();
return factory.CreateConnection();
});
Register Publisher¶
The exact registration depends on the descriptor configuration used by the application.
Conceptually:
services.AddSingleton<IAsyncPublisher>(
provider =>
{
// Build publisher
});
Register Subscriber¶
Conceptually:
services.AddSingleton<IAsyncSubscriber<OrderCreated>>(
provider =>
{
// Build subscriber
});
Resolve Publisher¶
var publisher =
serviceProvider
.GetRequiredService<IAsyncPublisher>();
Resolve Subscriber¶
var subscriber =
serviceProvider
.GetRequiredService<
IAsyncSubscriber<OrderCreated>>();
Recommended Usage¶
graph LR
Application --> ServiceProvider
ServiceProvider --> Publisher
ServiceProvider --> Subscriber
The application should depend on abstractions rather than constructing messaging components directly.