rebus-org / Rebus.ServiceProvider

:bus: Microsoft Extensions Dependency Injection container adapter for Rebus
https://mookid.dk/category/rebus
Other
67 stars 32 forks source link

Inject Incoming and Outgoing Steps outside of Options. #92

Closed mccow002 closed 5 months ago

mccow002 commented 5 months ago

My organization uses Rebus for it's service bus abstraction layer in all it's applications. This means we also have several internal libraries that require Incoming and Outgoing steps to work properly.

Currently, we create a static extension method off of OptionsConfigurer, so the consuming app has to do:

services.AddRebus(cfg => cfg
   // Other setup
   .Options(o => o.AddMyLibrariesCustomSteps())
);

This is in addition to a static extension method off of IServiceCollection to register everything else the library uses.

services.AddMyLibrary();

If it possible to access OptionsConfigurer outside of AddRebus -> Options? Can I combine registering the services and the rebus pipeline steps into a single method?

mookid8000 commented 5 months ago

Hi @mccow002 , I have no idea why I didn't see your question before now - sorry!

It's not possible to get a hold of OptionsConfigurer outside of the Rebus configuration callback.

But what you might want to investigate, is how you can combine registering other things in the container

services.AddSingleton<IMyThingy, DefaultThingy>();

with accessing the container (i.e. the IServiceProvider) in the callback passed to AddRebus, e.g. like

services.AddRebus((cfg, provider) => cfg
   // Other setup
   .Options(o => o.AddMyLibrariesCustomSteps(provider.GetRequiredService<IThingy>()))
);

Having access to IServiceProvider in the configuration callback enables all kinds of interesting scenarios, e.g. where your (singleton!) steps are registered in the container, or their (singleton!) dependencies are, or your steps get an IServiceScopeFactory injected making it possible for them to retrieve transient and scoped dependencies to carry out their work.

And all of this can be neatly packed away in a (possibly parameterized) high-level extension method, e.g. like

services.AddRebus("my-input-queue-name");

or whatever you chose to expose as the thing you want to vary from call to call.

Let me know if there's anything concrete you need help with wiring up. 🙂