mercredi 25 septembre 2019

Implementing the Options pattern with a class injected during ConfigureServices - AddScoped

I have a small class to obtain a series of information about my user on several of my MVC applications. A minimal reproducible example would be:

public class InformationGetter
    {
        public string GetUserInformation(string connectionStr, string storedProcedureName, int userId)
        {
            // Do SQL work
            return info;
        }
}

I'm injecting it on the ConfigureServices step using

services.AddScoped<InformationGetter>

And then in my classes I simply call it from the DI.

Now, obviously the connectionStr and storedProcedure only changes per application but right now I'm passing it as parameter.

I've tried to make those parameters public and configure it using services.Configure but when I call it from my controllers, I get null values.

            services.AddOptions();
            services.Configure<InformationGetter>(options =>
            {
                options.ConnectionString = Configuration.GetSection("Model").GetSection("ConnectionString").Value;
                options.StoredProcedureName = "prInformationGetter";
            });

I'm not sure if the reason why this is failing it's because I'm missing an interface on my original class or am I failing to understand this concept.

I've also thought on doing something like services.AddInformationGetter(options => {}) but my understanding is that this pattern is to implement middlewares and not DI specifically.

I tried checking the documentation (docs.microsoft.com) but I got even more confused.

Aucun commentaire:

Enregistrer un commentaire