简体   繁体   中英

How can I get IHostingEnvironment from DbContext in ASP.NET Core

Just for testing, I don't want to do dependency injection from StartUp.cs file. How can I get IHostingEnvironment from EF Core DBContext.

I take a new asp.net core project with empty template. I have created a dbcontext as below. I want to user Environment.ContentRootPath instead of Directory.GetCurrentDirectory(). But I don't want to do any injection from Startup.cs.

public class MyDBContext: DbContext
{

    public IConfigurationRoot Configuration { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var builder = new ConfigurationBuilder()
              .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "..\\..\\.."))
              .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
        Configuration = builder.Build();
        optionsBuilder.UseSqlServer(Configuration.GetConnectionString("SQLCN"));// @"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
    }

    public DbSet<Teacher> Teachers { get; set; }
    public DbSet<Lesson> Lessons { get; set; }
}

If I add IHostingEnvironment in dbcontext constructor as below,

public class MyDBContext: DbContext
{
    private readonly IHostingEnvironment env;
    public MyDBContext(IHostingEnvironment env) : base()
    {
        this.env = env;
    }


    public IConfigurationRoot Configuration { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var builder = new ConfigurationBuilder()
              .SetBasePath(this.env.ContentRootPath)
              .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
        Configuration = builder.Build();
        optionsBuilder.UseSqlServer(Configuration.GetConnectionString("SQLCN"));// @"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
    }

    public DbSet<Teacher> Teachers { get; set; }
    public DbSet<Lesson> Lessons { get; set; }
}

I got following error when I Add-Migration from Package-Manager console.

PM> Add-Migration InitMyDBContext

No parameterless constructor was found on 'MyDBContext'. Either add a parameterless constructor to 'MyDBContext' or add an implementation of 'IDbContextFactory' in the same assembly as 'MyDBContext'.

You should be able to inject the IHostingEnvironment directly into your DbContext's constructor.

public class MyDBContext: DbContext {
    private readonly IHostingEnvironment env;
    public MyDBContext(IHostingEnvironment env) : base() {
        this.env = env;
    }

    public IConfigurationRoot Configuration { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
        Configuration = builder.Build();
        optionsBuilder.UseSqlServer(Configuration.GetConnectionString("SQLCN"));// @"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
    }

    public DbSet<Teacher> Teachers { get; set; }
    public DbSet<Lesson> Lessons { get; set; }
}

The framework is already aware of the interface.

You add the context as usual. Minus configuration, as you indicated that you don't want to do it in Startup

services.AddDbContext<MyDBContext>();

when initializing the context the framework should inject an implementation of IHostingEnvironment into the context based on the presence of the constructor argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM