Skip to content

Avoid use BuildServiceProvider in startup code #41

@scorrao

Description

@scorrao

In ServiceBus.cs at Distribt.Shared.Setup call to BuildServiceProvider to access a list of handlers an create IMessageHandlerRegistry.

ServiceProvider sp = serviceCollection.BuildServiceProvider();
var listHandlers = sp.GetServices<IMessageHandler>();
serviceCollection.AddConsumerHandlers(listHandlers);

Call to BuildServiceProvider make problems with singletons services.

Calling BuildServiceProvider multiple times can cause serious trouble, because each call to BuildServiceProvider results in a new container instance with its own cache. This means that registrations that are expected to have the Singleton lifestyle, suddenly are created more than once. This is a problem called Ambiguous Lifestyle.
https://stackoverflow.com/a/66264937

Microsoft has a warning related
https://learn.microsoft.com/en-us/aspnet/core/diagnostics/asp0000?view=aspnetcore-8.0

I changed the constructor of MessageHandlerRegistry to able to get the necessaries services from ServiceProvider

-    public MessageHandlerRegistry(IEnumerable<IMessageHandler> messageHandlers)
+    public MessageHandlerRegistry(IServiceProvider serviceProvider)
    {
-        _messageHandlers = messageHandlers;
+        using (var scope =  serviceProvider.CreateScope())
+            _messageHandlers = scope.ServiceProvider.GetServices<IMessageHandler>();
    }

This change require change also multiple extension class to fix the dependency injection.
What do you think? i don't known if it can impact in another feature

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions