Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; }
}
like image 397
Martin Avatar asked Dec 24 '22 15:12

Martin


1 Answers

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;
like image 70
Joe Audette Avatar answered Jan 18 '23 23:01

Joe Audette