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)
    return services;

That’s it!

Service Lifetimes

Services can be registered with one of the following lifetimes:

  • Transient
  • Scoped
  • Singleton


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



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



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.


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] attribute in a Razor component code behind file to inject your services.

namespace MyApp.Pages.Developers.Index;

public partial class Index
    [Inject] public DeveloperService DeveloperService { get; set; }

	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.

Stay up to date with Spark on Twitter or our Newsletter

Looking for .NET jobs? Check out Dotnet Jobs for weekly job postings.