Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection in EF-core OnModelCreating method

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");
     }
    );
    ...
}
like image 436
Khodaie Avatar asked Sep 12 '25 20:09

Khodaie


1 Answers

Use

this.Database.GetService<IPasswordService>();

It's an extension method and sits in Microsoft.EntityFrameworkCore.Infrastructure namespace

like image 115
Artur Avatar answered Sep 14 '25 09:09

Artur