Kho*_*aie 1 c# dependency-injection .net-core ef-core-2.2
我想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");
}
);
...
}
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)
用
this.Database.GetService<IPasswordService>();
Run Code Online (Sandbox Code Playgroud)
这是一个扩展方法,位于Microsoft.EntityFrameworkCore.Infrastructure命名空间中
| 归档时间: |
|
| 查看次数: |
974 次 |
| 最近记录: |