Skip to content

Getting an instance of ICrudServices

Jon P Smith edited this page Jun 5, 2020 · 1 revision

Getting an instance of ICrudServices

To use GenericServices you need to get an instance of the ICrudServices/ICrudServicesAsync. Typically this is done via dependency injection (DI), but can be done manually. There are two parts to using DI

  1. You register GenericServices on startup
  2. You inject an instance of CrudServices by using the the correct version of the ICrudServices (there are two types, each with a sync/async version).

Working with one DbContext

The default usage of GenericServices is working with one DbContext.

Registering GenericServices

Look at Registering GenericServices - Registering one DbContext

Getting an instance of the CrudServices

You can inject via a constructor, or in ASP.NET Core MVC/Web API you can also use the [FromService] to inject via an action parameter. You should use either ICrudServices or ICrudServicesAsync to get the sync or async version respectively.

Here is and example of injecting via constructor from the RazorPageApp in the EfCore.GenericServices repo.

Working with multiple DbContext

EfCore.GenericServices can work with multiple DbContexts at the same time.

Registering GenericServices

Look at Registering GenericServices - Registering multiple DbContext

Getting an instance of the CrudServices

You can inject via a constructor, or in ASP.NET Core MVC/Web API you can also use the [FromService] to inject via an action parameter. You should use either ICrudServices<TContext> or ICrudServicesAsync<TContext> to get the sync or async version respectively. The TContext is the DbContext that you wish to use with this instance of the CrudServices .

Here is an example using the [FromServices] parameter injection from my EfCoreSqlAndCosmos project which uses three DbContexts.

Clone this wiki locally