简体   繁体   中英

Dependency Injection: Injecting configuration in .Net Core 2.0

I'm migrating some old software to .Net core 2.0 ...

I'd like to inject a connection string in my class DBActivityRepository from a base class...

Should I just pass the configuration in the creation of the base class

this._DBHandler = new DBHandler(configuration);

or is it better to do it this way:

private DBHandler _DBHandler;
private string connectionString;
public DBActivityRepository(IConfiguration configuration) : base(configuration)
{
    // **Do I need this?**
    this._DBHandler = new DBHandler(configuration);
    connectionString = this._DBHandler.GetConnectionString();
}

Thanks

For dependency injection in asp.net core you need to use built-in DI engine. At first, you need create appsetting.json.

"ConnectionStrings": {
    "NameOfContext":"server=localhost;userid=root;password=password;"
}

Second, create options type for connection strings and other properties what you need to read from appsettings.json.

For IServiceCollection services read properties from appsettings.json:

services.Configure<YourServiceOptions>(_config["ConnectionStrings:NameOfContext"])

And, the last step is init your db connection:

services.AddDbContext<NameOfContext>(builder => builder.UseMySql(options.ConnectionString));

This only works with MySql.

If DBHandler is your base class and DbActivityRepository is a subclass of DBHandler, is not necessary to create an instance of DBHandler into the DBActivityRepository, you can use their public and protected methods/properties directly (inheritance), something like this:

public interface IConfiguration
{
    string GetConnectionString();
}

public abstract class DbHandler
{
    protected DbHandler(IConfiguration configuration)
    {
        ConnectionString = configuration.GetConnectionString();
    }

    protected string ConnectionString { get; }
}

public class DbActivityRepository : DbHandler
{
    public DbActivityRepository(IConfiguration configuration) 
        : base(configuration)
    {
    }

    private void DoSomething()
    {
        // use your connStr
        Console.Write(ConnectionString);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM