Services

Introduction

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.

Creating Services

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()
    {
    }
}

Registering Services

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!

Service Lifetimes

Services can be registered with one of the following lifetimes:

  • Transient
  • Scoped
  • Singleton

Transient

Transient lifetime services create a new instance each time the service is requested.

services.AddTransient<MyService>();

Scoped

Scoped lifetime service get create a new instance 1 time per web request.

services.AddScoped<MyService>();

Singleton

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>();

Injecting Services

Once a service is registered, it can be injected into any Razor component or other registered classes.

Injecting a Service in a Razor component

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();
    }
}

Injecting a service into another service

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 and ProjectService must be registered in your apps DI container.