在DatabaseInitializer中獲取IHostingEnvironment.ContentRootPath

.net-core asp.net-core entity-framework-core

我正在嘗試使用存儲在json文件中的一些數據來播放我的數據庫。

我需要在我的IHostingEnvironment IDatabaseInitializer.Seed()方法中註入一個IHostingEnvironment這樣我就可以使用IHostingEnvironment.ContentRootPath讀取json文件。

默認情況下,此屬性由主容器注入,但DbConfiguration的構造DbConfiguration必須是無參數的,因此我無法通過DbConfigurationIHostingEnvironment DbConfigurationSetDatabaseInitializer(new DatabaseInitializer())

/*
* Database Context
*/
[DbConfigurationType(typeof(DatabaseConfiguration))]
public class DatabaseContext : DbContext
{
    public DbSet<User> Users { get; set; }

    public DatabaseContext(string nameOrConnectionString) : base(nameOrConnectionString) { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
        base.OnModelCreating(modelBuilder);
    }
}

/*
* Database Configuration
*/
public class DatabaseConfiguration : DbConfiguration
{
    // Can't receive injected IHostingEnvironment env because constructor must be parameterless
    public DatabaseConfiguration()
    {
        SetProviderServices("System.Data.SqlClient", SqlProviderServices.Instance);

        // Could pass IHostingEnvironment through constructor
        SetDatabaseInitializer(new DatabaseInitializer()); 
    }
}

/*
* Database Initializer
*/
public class DatabaseInitializer : DropCreateDatabaseAlways<DatabaseContext>
{
    private readonly IHostingEnvironment env;

    // Receives IHostingEnvironment from DatabaseConfiguration
    public DatabaseInitializer(IHostingEnvironment env)
    {
        this.env = env;
    }

    protected override void Seed(DatabaseContext context)
    {
        // Read some .json files
    }
}

熱門答案

我正在初始化我的數據庫,並且必須編寫一個單獨的類,我從configure調用,你可以做同樣的事情並傳入路徑作為參數

以下是我稱之為:

        using (var scope = scopeFactory.CreateScope())
        {
            // Initialise Database
            var initializer = scope.ServiceProvider.GetService<IDbInitializer>();
            initializer.SeedAsync().Wait();

            // initialize plugin manager
            var manager = scope.ServiceProvider.GetService<IPluginManager>();
            manager.Initialize(dbConnection);
            if (Configuration.GetSection("PluginService").GetValue<bool>("RunAtStartup") == true)
                manager.Start();
        }

這是db初始化類

    public interface IDbInitializer
{
    Task SeedAsync();
}

public class DbInitializer : IDbInitializer
{
    private ApplicationDbContext _context;
    private RoleManager<IdentityRole> _roleManager;
    private UserManager<ApplicationUser> _userManager;

    public DbInitializer(ApplicationDbContext context,
                         RoleManager<IdentityRole> roleManager,
                         UserManager<ApplicationUser> userManager)
    {
        _context = context;
        _roleManager = roleManager;
        _userManager = userManager;
    }

    public async Task SeedAsync()
    {
        await CreateRolesAsync();
        await CreateAdminUserAsync();
        await SeedMenuAsync();
    }

    private async Task CreateRolesAsync()
    {
        List<IdentityRole> roles = new List<IdentityRole>();
        roles.Add(new IdentityRole { Name = "Admin", NormalizedName = "ADMINISTRATOR" });
        roles.Add(new IdentityRole { Name = "Member", NormalizedName = "MEMBER" });                     // An email confirmed memeber
        roles.Add(new IdentityRole { Name = "Guest", NormalizedName = "GUEST" });                       // Used for a user that has only checked out as guest
        roles.Add(new IdentityRole { Name = "NotConfirmed", NormalizedName = "NOTCONFIRMED" });         // Used when a guest hasnt confirmed there registration

        foreach (var role in roles)
        {
            var roleExists = await _roleManager.RoleExistsAsync(role.Name);
            if (!roleExists)
            {
                await _roleManager.CreateAsync(role);
            }
        }
    }

    ...

希望有所幫助



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow