Implementing Dependency Injection in NET Core 3.1 with Factory Pattern

Feedback


Solution:

There is no issue with restarting the system after modifying the configuration.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton(Configuration);
    services.AddScoped();
    services.AddScoped();
    var messageProvider = Configuration.GetConfig("MessageService", "Messaging_Service");
    switch(messageProvider)
    {
        case "AzureServiceBus": 
            services.AddScoped();
            break;
        case "RabbitMq": 
            services.AddScoped();
            break;
        default: 
            throw new ArgumentException("Invalid message service");
    };
    services.AddControllers();
}


Other note

I observed that you provided a factory alongside the concrete type.


services.AddScoped<IMessagingService, MassTransitAzureServiceBusMessagingService>(s => s.GetService<MassTransitAzureServiceBusMessagingService>());

I think it should be:


services.AddScoped<IMessagingService>(s => s.GetService<MassTransitAzureServiceBusMessagingService>());

Not sure it it makes a difference.

In January 2021, I was faced with the task of finding a solution to a problem and ultimately came up with my own approach.

public static IServiceCollection ConfigureEventBus(this IServiceCollection services, IConfiguration configuration)
{
    var queueSettings = new QueueSettings();
    configuration.GetSection("QueueSettings").Bind(queueSettings);
    if (configuration.GetValue("AzureServiceBusEnabled"))
    {
        services.AddMassTransit(x =>
        {
            x.UsingAzureServiceBus((context, cfg) =>
            {
                cfg.Host(queueSettings.HostName);
            });
        });
    }
    else
    {
        services.AddMassTransit(x =>
        {
            x.UsingRabbitMq((context, cfg) =>
            {
                cfg.ConfigureEndpoints(context);
                cfg.Host(queueSettings.HostName, queueSettings.VirtualHost, h =>
                {
                    h.Username(queueSettings.UserName);
                    h.Password(queueSettings.Password);
                });
            });
        });
    }
    services.AddMassTransitHostedService();
    services.AddSingleton();
    return services;
}


Frequently Asked Questions

Posted in Uncategorized