I created an ASP.NET class library in my ASP.NET5 application. I wanted to add a file Startup.csto load some configuration from a .json file (ConnectionString), to use it in the project and add it to the DI. Then I wanted to enter AppSettingsinto mine DbContext, which is in the same project. But this does not work, it seems that the code in the Startup class is never executed.
Entering AppSettingsin the DbContextthrows Exception
InvalidOperationException: Unable to resolve service for type 'Beo.Dal.Properties.AppSettings' while attempting to activate 'Beo.Dal.DataContexts.ApplicationDbContext'.
Dbcontext
private static bool IsCreated;
private AppSettings AppSettings;
public ApplicationDbContext(AppSettings settings)
{
AppSettings = settings;
if (!IsCreated)
{
Database.AsRelational().ApplyMigrations();
IsCreated = true;
}
}
Am I missing something or am I misunderstanding? I already have one Startup.csin the MVC project and it works great. Can I use it in a class library? If not, how do I download this .json?
This is what I really did inside:
public class Startup
{
public AppSettings Settings { get; set; }
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
builder.AddEnvironmentVariables();
Configuration = builder.Build();
Settings = new AppSettings();
}
public void Configure(IApplicationBuilder app)
{
string connectionString;
if (Configuration.TryGet("Data:DefaultConnection:ConnectionString", out connectionString))
{
Settings.ConnectionString = connectionString;
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddInstance(Settings);
}
}