I have my connection string in appsettings.json in my API project which I want use in my context in my Database project. Usually, dependency injection does the trick, however, when I run migrations I get this error:
Unable to create an object of type 'Context'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728!
Hard-coding the connection string in the context fixes this problem but is not a viable solution for me as I need to change the connection string depending on environment. Please see my ConfigureServices method from the API project and the context from the Database project.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed
// for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddDbContext<Context>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public class Context : DbContext
{
private readonly IOptions<AppSettings> _settings;
public Context(IOptions<AppSettings> settings) : base()
{
_settings = settings;
}
public Context(IOptions<AppSettings> settings, DbContextOptions<Context> options) : base(options)
{
_settings = settings;
}
***DBSets***
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_settings.Value.DBConnectionString);
}
}
_settings.Value.DBConnectionString
is not getting the connection string.optionsBuilder.UseSqlServer(_settings.Value.DBConnectionString);
code toConfigureServices
method in Startup class? if not then I can give a solution.