Home > other >  Replace EF Core service with instance instead of type
Replace EF Core service with instance instead of type

Time:12-21

In a non-ASP.NET environment (e.g. console programme, unit tests or dotnet ef CLI tool) I can replace EF Core services using DbContextOptionsBuilder:

builder.ReplaceService<IRelationalDatabaseCreator, MyCreator>();
builder.ReplaceService<IMigrationsAssembly, MyAssembly>();

For MyCreator or MyAssembly, it uses the type and its default constructor. How do I replace a service with an instance instead (that I can customize)?

Some (invalid) code to show what I mean:

var myCreator = new MyCreator("foo", 123);
builder.Replace<IRelationalDatabaseCreator>(myCreator);

CodePudding user response:

How do I replace a service with an instance instead (that I can customize)?

You can't.

For MyCreator or MyAssembly, it uses the type and its default constructor.

That's not quite correct (otherwise you won't be able to replace EF Core services with dependencies).

The specified service implementation type instance is resolved from DI container as any other, so you can use any existing constructor dependency injection mechanisms to configure it (for instance, similar to how EF Core provides configured DbContextOptions to the DbContext constructor). The only specific here is that these dependencies must be registered in the app service container (where the DbContext is registered) since the builder does not allow registering services.

  • Related