Sam
Sam

Reputation: 113

.NET CORE 2.1 Constructor asks for IConfiguration

I've followed several methods on StackOverflow to fix my issue, none with a result:

My DefaultConnection-string is in my AppSettings.json. To retrieve info I am reading to use the IConfiguration from my startup.cs. The constructor of my MsSQL-context is still asking for this IConfiguration. Note: I'm using a repository pattern.

startup.cs:

public Startup(IConfiguration configuration)
        {
            this.Configuration = configuration;
        }
public IConfiguration Configuration { get; private set; }
 public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IConfiguration>(Configuration);

I've added the Singleton in my startup after a suggestion. With or without this the constructor of MsSQLContext is still requesting this as a variable to be passed. Leaving the constructor without this gives me the error: Connectionstring not initialized.

AdminMsSQLContext:

        private readonly string _connectionString;


    public MSSQLAdminContext(IConfiguration configuration)
    {
        _connectionString = configuration.GetConnectionString("DefaultConnection");
    }

Upvotes: 1

Views: 1873

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239420

Injecting IConfiguration is actually an anti-pattern, anyways. What you should be doing is supplying an action to your scope registration and change your MSSQLAdminContext class to accept just the connection string in its constructor:

public MSSQLAdminContext(string connectionString)
{
    _connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
}

Then:

services.AddScoped(_ =>
    new MSSQLAdminContext(Configuration.GetConnectionString("DefaultConnection)));

Your repo should not have knowledge of something like your configuration. If it needs a connection string, then it should take the connection string, and that is all.

Upvotes: 3

E McG
E McG

Reputation: 289

I believe the issue you are having is that you have not registered the MSSQLAdminContext with the DI container. Because of this the DI engine does not know to inject the IConfiguration into the class. In your start up you will register this class however you need, I tend to use scoped for these types of classes you may use in multiple places. So something like this.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<MSSQLAdminContext>();
            services.AddSingleton<IConfiguration>(Configuration);
        }

Upvotes: 0

Related Questions