c# - EF-core OnModelCreating 方法中的依赖注入
问题描述
我想OnModelCreating
在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");
}
);
...
}
上面的代码可以替换为:
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");
}
);
...
}
解决方案
采用
this.Database.GetService<IPasswordService>();
它是一种扩展方法,位于Microsoft.EntityFrameworkCore.Infrastructure
命名空间中