EF核心OnModelCreating方法中的依赖注入

时间:2019-08-05 04:25:29

标签: c# dependency-injection .net-core ef-core-2.2

我想在OnModelCreating的{​​{1}}方法中调用自己的某些服务。我该怎么办?

我可以通过DbContext构造函数注入服务。但这似乎还不够有效,因为该方法在应用程序启动时被调用一次,因此我必须为此加满整个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");
     }
    );
    ...
}

1 个答案:

答案 0 :(得分:3)

使用

this.Database.GetService<IPasswordService>();

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