rebus-org / Rebus.ServiceProvider

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

Example for template Worker #53

Closed kostazol closed 2 years ago

kostazol commented 2 years ago

Please make example for Worker template, where we don't have Configure method.

        public override Task StartAsync(CancellationToken cancellationToken)
        {
            var services = new ServiceCollection();
            using (var provider = services.BuildServiceProvider())
            {
                provider.UseRebus();
            }
            _logger.LogWarning("Hangfire Server started at: {time}", DateTimeOffset.Now);
            return base.StartAsync(cancellationToken);
        }

I think about this, but maybe it isn't correct. If queue exsist, it will work without calling method UseRebus, because i don't understand purpose of call UseRebus method.

kostazol commented 2 years ago

I found example and it made as I wrote. https://github.com/danielh1/rebus-onboardingcs/tree/1df8276a75df4a3d3bc303f4e9860f071284d0e3/OnboardingWorkerService

But MSDN recommend avoid calls to BuildServiceProvider ... https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0

mookid8000 commented 2 years ago

The example here is how it's done: https://github.com/danielh1/rebus-onboardingcs/blob/1df8276a75df4a3d3bc303f4e9860f071284d0e3/OnboardingWorkerService/RebusWorker.cs

(...) But MSDN recommend avoid calls to BuildServiceProvider (...)

No. MSDN says to avoid calling BuildServiceProvider IN ConfigureServices:

image

This is because ConfigureServices is a callback where you are supposed to configure your service collection, and then the generic host will build the service provider. That is, if you built the service provider in the callback, you would have your own little local service provider instance, possibly with an incomplete configuration.

There's no problem with tossing you own service provider instances around, as long as you do it in a disciplined manner 🙂 and having a service provider inside a background worker will not cause you any trouble, it will simply work a neatly packaged root of your Rebus application.