Documentation Menu
Services are regular C# classes where you can tuck away business logic or data access methods to make them re-usable throughout your application.
On top of this, Spark makes it easy to add your services to the DI Container.
To create a Service, simply use the Spark make service
command.
spark make service DeveloperService
A new class in the Application/Services
folder will be created.
public class DeveloperService
{
public DeveloperService()
{
}
}
Before you’re able to inject and use your service, you need to register it in the DI container. Spark makes this easy.
Simply add your service to the AddCustomServices
method in the Application/Startup/AppServiceRegistration.cs
class.
private static IServiceCollection AddCustomServices(this IServiceCollection services)
{
...
services.AddScoped<DeveloperService>();
return services;
}
That’s it!
Services can be registered with one of the following lifetimes:
Transient lifetime services create a new instance each time the service is requested.
services.AddTransient<MyService>();
Scoped lifetime service get create a new instance 1 time per web request.
services.AddScoped<MyService>();
Singleton lifetime services will last the entire lifetime of the application. For web apps, that means after the first request of the service, every subsequent request will use the same instance.
services.AddSingleton<MyService>();
Once a service is registered, it can be injected into any Razor component or other registered classes.
Use the Inject
directive in a Razor component to inject your services.
@page "/"
@inject DeveloperService DeveloperService
@code {
private List<Developer> _developers;
protected override void OnInitialized()
{
_developers = await DeveloperService.GetAll();
}
}
Use standard dependency injection.
public class DeveloperService
{
private readonly ProjectService _projectService;
public DeveloperService(ProjectService projectService)
{
this._projectService = projectService;
}
public List<projects> GetDevelopersProjects(int developerId)
{
return this._projectService.GetProjectsByDeveloperId(developerId);
}
}
For this to work, both the
DeveloperService
andProjectService
must be registered in your apps DI container.