0

VS2022 NetCore 6 EF 6

    builder.Services.AddDbContext<MyAppDbContext>(options removed for simplicity)

    //This is my service registered on Program.cs:
    builder.Services.AddScoped<AccountService>();
    
    //This is the existing class that works as expected:
    public class AccountService
    {
     private readonly MyAppDbContext _context;  
     public AccountService(MyAppDbContext context)
       {
          _context = context;
       }
    }
    //So far so good... 
    
    // Now I need to add another parameter to the service:
    public class AccountService
    {
     private readonly MyAppDbContext _context;  
     public AccountService(MyAppDbContext context, string newParameter)
       {
          _context = context;
          string temp = newParameter;
       }
    }
    
    // But I cannot register; I don't know what to put as first value and if I put MyAppDbContext it gives an error saying it is a type.
    
    builder.Services.AddScoped(ServiceProvider => { return new AccountService(??, newParameter);});

// This works (no compile error) for newParameter but ignores DbContext
    builder.Services.AddScoped(ServiceProvider => { return new AccountService( **null**, newParameter);});
Ben Junior
  • 2,449
  • 10
  • 34
  • 51
  • Check out this answers to this similar question: https://stackoverflow.com/questions/53884417/net-core-di-ways-of-passing-parameters-to-constructor – Drew Brasher Dec 03 '21 at 18:15
  • I did. I have no problem creating a service with parameters. My issue is that I don't know how to pass the first one as dbContext. Please see edited question – Ben Junior Dec 03 '21 at 21:28

1 Answers1

1

You registration will become a little uglier:

builder.Services.AddScoped<AccountService>(x => new AccountService( 
     x.GetRequiredService<MyAppDbContext>(),
     newParameter));

It is important to let the ServiceProvider create the (scoped) DbContext each time you need an AccountService.

H H
  • 263,252
  • 30
  • 330
  • 514