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; }
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With