I want to invoke some of my own services in the OnModelCreating
method of the DbContext
. What do I need to do?
I can inject the service via the DbContext
constructor. But it doesn't seem effective enough as the method is called once on the application startup and I have to fatten my entire DbContext class for it.
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");
}
);
...
}
Can the above code be replaced with the one:
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");
}
);
...
}
Use
this.Database.GetService<IPasswordService>();
It's an extension method and sits in Microsoft.EntityFrameworkCore.Infrastructure
namespace
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With