Francois
Francois

Reputation: 159

How to properly call a method at startup in Asp .Net Core?

I would like to reuse a library class that I made for some projects in Asp .Net Framework within an Asp .Net Core project on which I am now working.

For that project I have to use a MySQL database so I added the MySqlConnector NuGet package to my library class.

As the registered .NET Data Providers are not automatically added to the Global Assembly Cache I must register it manually thanks the call of that method DbProviderFactories.RegisterFactory("MySqlConnector", MySqlClientFactory.Instance) during application startup as mentionned here.

It's my first .Net core project so I don't know if that's how I should do it but I called that method in the Startup.cs file like this :

enter image description here

It is working but I am wondering if it's the right way to do it. Would you advise me another proper way to do it?

Thanks

Upvotes: 1

Views: 4036

Answers (1)

Ricardo Peres
Ricardo Peres

Reputation: 14555

There is nothing fundamentally wrong with your approach, IMO. One problem I see is the task you're trying to run takes too long, in which case you're better off spawning a task. The other is reusability, your code is coupled together. You could solve that by wrapping it in a class and injecting it into a middleware component by interface, and then calling a method. For example:

public interface ITask { void Run(); }

class RegisterMySqlTask : ITask { public void Run() { DbProviderFactories.RegisterFactory("MySqlConnector", MySqlClientFactory.Instance); } }

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ITask, RegisterMySqlTask>();
    //rest goes here
}

public void Configure(IApplicationBuilder app)
{
    app.Use(async (context, next) =>
    {
        context.RequestServices.GetRequiredService<ITask>().Run();
        await next(context);
    });

    //rest goes here
}

Note, however, that this may be overcomplicating things. As I said, I believe that you are not doing anything wrong.

Upvotes: 4

Related Questions