rebus-org / Rebus

:bus: Simple and lean service bus implementation for .NET
https://mookid.dk/category/rebus
Other
2.27k stars 354 forks source link

Automatically register handlers #886

Closed christophebourguignon closed 4 years ago

christophebourguignon commented 4 years ago

Hi,

In a .Net 4.8 project, I would like to automatically register all assembly handlers. In .Net Core it's easy to do this with the AutoRegisterHandlersFromAssembly method. But in .Net 4.8, I can find all the handlers via reflection, but I can't register them. Do you have any sample code that does this?

Thank you in advance.

mookid8000 commented 4 years ago

Which container are you using?

christophebourguignon commented 4 years ago

Which container are you using?

I am using the BuiltinHandlerActivator

mookid8000 commented 4 years ago

Ok – it's not possible with BuiltinHandlerActivator.

Some of the other container integration packages come with handy extension methods for the container, like you've already discovered, so you can e.g.

services.AutoRegisterHandlersFromAssemblyOf<SomeHandler>();

with Microsoft's DI container.

The built-in handler activator doesn't use reflection to create your handlers, so it requires that you register your handlers either as callbacks or as factory methods.

If it were to auto-register a handler, it would have to create its own factory method somehow, thus beginning to move it too far into the DI container domain.

If you want to automatically discover and register your handlers, my suggestion is that you use a DI container (like Microsoft's, including the extensions that Rebus provides) to do that. This will have the added benefit that you can have dependencies injected, lifestyles managed, etc.

I hope that's alright with you. 🙂

christophebourguignon commented 4 years ago

Thank you for that prompt response. I will consider using a DI container.

Thanks.