Injecting Env Conn String into .NET Core 2.0 w/EF Core DbContext in different class lib than Startup prj & implementing IDesignTimeDbContextFactory

后端 未结 2 1115
温柔的废话
温柔的废话 2020-12-15 05:38

I honestly cannot believe how hard this is...first off the requirements that I am going for:

  • Implementing Entity Framework Core 2.0\' IDesignTimeDbContex
2条回答
  •  执笔经年
    2020-12-15 06:03

    I am a bit confused with your question. Are you using dependency injection for the DbContext or are you trying to initialize and construct the context ad hoc?

    I am doing what you have described in one of my solutions. Here is my solution structure:

    • Corp.ApplicationName.Data
    • Corp.ApplicationName.Web

    Startup.cs

    public Startup(IHostingEnvironment env)
    {
        IConfigurationBuilder builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", false, true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json")
            .AddEnvironmentVariables();
        // ...
    }
    
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddDbContext(
            options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
            sqlOptions => sqlOptions.EnableRetryOnFailure()));
    
        // SQL configuration for non-injected dbcontext
        DbContextOptionsBuilder builder = new DbContextOptionsBuilder();
        builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
        services.AddSingleton(builder.Options);
    
        // ...
    }
    

    MyDbContext.cs

    public class MyDbContext : IdentityDbContext
    {
        public MyDbContext(DbContextOptions options) : base(options) { }
    }
    

    If you are not using dependency injection to pass the DbContext, you can access the SQL properties by injecting DbContextOptions instead.

    In this example, the appsettings file is only every read once and everything just works.

提交回复
热议问题