Skip to content

Dependency Injection

ServiceBus.Core does not require a specific dependency injection container.

Publishers, subscribers and related infrastructure can be constructed manually or resolved through any dependency injection framework.

The documentation focuses on two common approaches:

  • Microsoft.Extensions.DependencyInjection
  • ServiceResolver.Ioc.SimpleInjector

Why Use Dependency Injection?

Dependency injection centralizes component construction and lifetime management.

Instead of manually creating publishers and subscribers:

graph LR

    Application --> Publisher

    Application --> Subscriber

the container becomes responsible for object creation.

graph LR

    Application --> Container

    Container --> Publisher

    Container --> Subscriber

Typical Dependencies

Publishers and subscribers generally depend on:

  • RabbitMQ connection infrastructure;
  • channels;
  • IDataFormatter;
  • descriptors.
graph TD

    Connection

    Channel

    Formatter

    Descriptor

    Publisher

    Subscriber

    Connection --> Publisher
    Connection --> Subscriber

    Channel --> Publisher
    Channel --> Subscriber

    Formatter --> Publisher
    Formatter --> Subscriber

    Descriptor --> Publisher
    Descriptor --> Subscriber

Lifetime Recommendations

Connection

Recommended lifetime:

Singleton

Formatter

Recommended lifetime:

Singleton

Descriptors

Recommended lifetime:

Singleton

Publishers

Recommended lifetime:

Singleton

unless application requirements dictate otherwise.


Subscribers

Usually created during application startup and kept alive for the application lifetime.


Manual Construction vs DI

Manual construction is useful:

  • in demos;
  • in tests;
  • for learning purposes.

Dependency injection is recommended for production applications.