-
Notifications
You must be signed in to change notification settings - Fork 96
Installing GenericServices
This page tells you how to set up GenericServices in your application. The steps are:
- Install the EfCore.GenericServices NuGet library in the main application so that
- You can register it with .NET Core dependency injection (DI) service, and...
- ... you can use
ICrudServices
in your front-end code.
- Install the EfCore.GenericServices library in the project/assembly where your DTOs are,
so that you can apply the
ILinkToEntity<TEntity>
interface to mark the DTOs.
Once you have installed the EfCore.GenericServices NuGet in your ASP.NET Core application
you need to register it in the ConfigureService
method in the Startup.cs
class.
The simplest approach, which assumes you have one application's DbContext, can be done
with one extension method called GenericServicesSimpleSetup<TContext>
. You can see how I did
this my the RazorPageApp here, but I have repeated the code below.
services.GenericServicesSimpleSetup<EfCoreContext>(
Assembly.GetAssembly(typeof(BookListDto)));
The key parts are:
- You must provide the type of your application's DbContext, and that context must have already been
registered with DI. GenericServices will register all the entity classes and also register your
application's DbContext against the
DbContext
class. - You need to provide the assemblies that your DTOs are in. I do this by using
GetAssembly
of one of my DTOs.
Advanced notes:
- GenericServices can handle multiple DbContexts (known in DDD as bounded contexts). To configure these you need to use a more complex registration arrangement, as shown below
services.ConfigureGenericServicesEntities(typeof(BookDbContext), typeof(OrderDbContext))
.ScanAssemblesForDtos(Assembly.GetAssembly(typeof(BookListDto)))
.RegisterGenericServices();
I describe this in the GenericServices and DTOs page.
I have an extension method called CopyErrorsToModelState
, which converts the GenericServices' IStatusGeneric
into errors in the ASP.NET Core ModelState
. All the example razor pages uses this - here is an example
public void OnGet(int id)
{
Data = _service.ReadSingle<AddReviewDto>(id);
//The service will have an error (i.e. _service.IsValid is false)
//if there is no entity with that id
if (!_service.IsValid)
{
//This will copy any errors to the ModelState
//if any of the errors have a property name that matches the Data class
//then adds that name to error message will appear next to the input field
//NOTE: For razor pages you need to prefix the property name with the name
//of the PageModel property, which is provided as the third param
_service.CopyErrorsToModelState(ModelState, Data, nameof(Data));
}
}
To use this you need to add the NuGet Library called EfCore.GenericServices.AspNetCore to your ASP.NET Core application.