无法解析类型' DatabaseConfiguration'在尝试激活“MyDbContext'

时间:2015-08-12 19:42:42

标签: .net asp.net-mvc asp.net-web-api dependency-injection asp.net-core

我在ASP.NET MVC Beta 6中使用依赖注入时遇到问题。在Startup.ConfigureServices方法中,我注册了DatabaseConfiguration和MyDbContext类。项目启动时,我收到以下错误:

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

我不确定为什么这样做无法解析DatabaseConfiguration类型。据我所知,它已正确注册。

我错过了什么?

// 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; }
}

1 个答案:

答案 0 :(得分:10)

你的config.json应该是这样的:

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

然后你的DI代码应该是这样的:

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

然后你真正得到的是

IOptions<DatabaseConfiguration> 

因此您需要更改DBContext的构造函数以接收

然后在你的DBContext中,你得到如下的连接字符串:

string connectionString = databaseConfiguration.Options.ConnectionString;

或者您可以获得像

这样的DatabaseConfiguration实例
DatabaseConfiguration dbConfig = databaseConfiguration.Options;