user3807918
user3807918

Reputation: 375

Getting Connection String in ASP.Net Core MVC data layer

I am using the code below to retrieve the connection string and it works fine. However, the configuration object has to be passed through the layers. Previous versions of .Net would allow me to get the connection string directly in the data layer. So can I still do that (and how do I do that) or do I need to pass the configuration object through the application as I do now?

In startup.cs

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
   ...
   services.AddSingleton(_ => Configuration);
   ...
}

MyController.cs

public class MyController : Controller
{
  protected readonly IConfiguration Configuration;

  public MyController(IConfiguration configuration)
  {
     Configuration = configuration;
  }

  public IActionResult ListRecords()
  {
      DatabaseContext ctx = new DatabaseContext(Configuration);
      return View();
  }
}

DatabaseContext.cs

public class DatabaseContext : DbContext
{
   private readonly IConfiguration config;
   public DatabaseContext(IConfiguration config)
   {
      this.config = config;
   }

   protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
   {
      optionsBuilder.UseSqlServer(config["ConnectionStrings:Dev"]);
   }
}

Upvotes: 0

Views: 1844

Answers (3)

Laxmikant
Laxmikant

Reputation: 588

use nugget packaeges

Install-Package Microsoft.Extensions.Configuration.Abstractions

 Install-Package Microsoft.Extensions.Configuration

and then Inject IConfigurationSection in the web application.

https://github.com/geeksarray/read-appsettings-json-in-net-core-class-library-using-dependency-injection

Upvotes: 0

WiseGuy
WiseGuy

Reputation: 429

Typically the pattern I've used for setting up DBContext, is to configure at startup.

So if this is startup.cs:

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var sqlConnString = Configuration.GetConnectionString(dbConnectionStringSettingsName);

            services.AddDbContext<DatabaseContext >(opt => opt.UseSqlServer(sqlConnString));

Also, if you pass your context as a service reference, you shouldn't need to give it IConfiguration.

    private readonly DatabaseContext _context;       

    public MyController(DatabaseContext context)
    {
        _context = context;
    }
    public IActionResult ListRecords()
    {
      var dbresults = _context.Table.ToList();
      return View(dbresults );
    }

Upvotes: 1

Nkosi
Nkosi

Reputation: 246998

Having to explicitly inject IConfiguration is usually seen as a code smell and indicates design issues.

Take advantage of dependency injection

public class MyController : Controller {
    DatabaseContext context;

    public MyController(DatabaseContext context) {
        this.context = context;
    }

    public IActionResult ListRecords() {
        //...use context here
        return View();
    }
}

and inject the database options instead

public class DatabaseContext : DbContext {    
    public DatabaseContext(DbContextOptions<DatabaseContext> options): base(options) {
        //...
    }
}

Then it is only a matter of configuring the context at startup

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services) {
    // ...

    services.AddDbContext<DatabaseContext>(options => 
        options.UseSqlServer(Congiguration.GetConnectionString("Dev"));

    // ...
}

Upvotes: 1

Related Questions