Unable to resolve service for type 'DatabaseConfiguration' while attempting to activate 'MyDbContext'

13,016

your config.json should be like this:

{
  "DatabaseConfiguration": {
      "ConnectionString": "yourconnectionstringhere"
    }
}

then your DI code should be like this:

services.Configure<DatabaseConfiguration>(configuration.GetConfigurationSection("DatabaseConfiguration"));

but then what you really get is an

IOptions<DatabaseConfiguration> 

so you need to change the constructor of your DBContext to receive that

then inside your DBContext, you get the connectionstring like:

string connectionString = databaseConfiguration.Options.ConnectionString;

or you could get the instance of DatabaseConfiguration like

DatabaseConfiguration dbConfig = databaseConfiguration.Options;
Share:
13,016
Martin
Author by

Martin

Updated on June 14, 2022

Comments

  • Martin
    Martin almost 2 years

    I am having issues using Dependency Injection in ASP.NET MVC Beta 6. In the Startup.ConfigureServices method, I register the class DatabaseConfiguration and MyDbContext. When the project starts, I get the following error:

    Unable to resolve service for type 'DatabaseConfiguration' while attempting to activate 'MyDbContext'.
    

    I am not sure to understand why this it's not possible to resolve the type DatabaseConfiguration. As far as I can tell, it is properly registered.

    What am I missing?

    // ASP.NET 5 Beta 6 Project 
    public void ConfigureServices(IServiceCollection services) {
        services.Configure<DatabaseConfiguration>(appSettings => ConfigurationBinder.Bind(appSettings, this.Configuration.GetConfigurationSection(nameof(DatabaseConfiguration))));
    
        services.AddTransient<MyDbContext>();
    
        services.AddMvc();
    }
    
    public class ValuesController : Controller {
        public ValuesController(MintoDbContext tenantRepo) { // ... }
    
        // ...
    }
    
    // The following classes are in a Class Libary.
    public class MyDbContext : DbContext {
        public MyDbContext(DatabaseConfiguration databaseConfiguration) { // ... }
    }
    
    public class DatabaseConfiguration {
        public string ConnectionString { get; set; }
    }