EF-core OnModelCreating 方法中的依赖注入

Kho*_*aie 1 c# dependency-injection .net-core ef-core-2.2

我想OnModelCreatingDbContext. 我需要做什么?

我可以通过DbContext构造函数注入服务。但它似乎不够有效,因为该方法在应用程序启动时被调用一次,我必须为它增肥我的整个 DbContext 类。

public PortalContext(DbContextOptions<PortalContext> options, IPasswordService passwordService) : base(options)
{
    this._passwordService = passwordService;
}

...

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    ...
    entity<User>().HasData(
     new User
     {
       UserName = "admin",
       Password = this._passwordService.EncryptPassword("passw0rd");
     }
    );
    ...
}
Run Code Online (Sandbox Code Playgroud)

上面的代码可以替换为:

public PortalContext(DbContextOptions<PortalContext> options) : base(options)
{
}

...

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    ...
    var passwordService = GetPasswordService(); // How?
    entity<User>().HasData(
     new User
     {
       UserName = "admin",
       Password = passwordService.EncryptPassword("passw0rd");
     }
    );
    ...
}
Run Code Online (Sandbox Code Playgroud)

Art*_*tur 6

this.Database.GetService<IPasswordService>();
Run Code Online (Sandbox Code Playgroud)

这是一个扩展方法,位于Microsoft.EntityFrameworkCore.Infrastructure命名空间中

  • 您应该在“IDesignTimeDbContextFactory”类中注册此服务。 (2认同)