This guide explains the process of creating and implementing services in the KikiWriting backend application.
- Define an interface
- Implement the interface
- Register the service in the dependency injection container
- Inject the service into controllers or other services
Create your services in the Services
directory, organized by feature:
Services/
├── FeatureName/
│ ├── IFeatureService.cs # Interface defining the service contract
│ ├── FeatureService.cs # Concrete implementation of the service
│ └── Models/ # Feature-specific models (if needed)
First, define the service contract with an interface:
namespace Services.FeatureName;
public interface IFeatureService
{
Task<ResultType> DoSomethingAsync(InputType input);
ResultType DoSomethingElse(InputType input);
}
Next, implement the interface:
namespace Services.FeatureName;
public class FeatureService : IFeatureService
{
private readonly ILogger<FeatureService> _logger;
private readonly IConfiguration _configuration;
// Inject other dependencies as needed
public FeatureService(
ILogger<FeatureService> logger,
IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}
public async Task<ResultType> DoSomethingAsync(InputType input)
{
_logger.LogInformation("Doing something with {Input}", input);
// Implementation code here
return result;
}
public ResultType DoSomethingElse(InputType input)
{
// Implementation code here
return result;
}
}
Add your service to the ConfigureServices
method in ServicesInjector.cs
:
// In ServicesInjector.cs
public static void ConfigureServices(WebApplicationBuilder builder)
{
// ... existing registrations ...
// Feature service
builder.Services.AddScoped<Services.FeatureName.IFeatureService,
Services.FeatureName.FeatureService>();
}
Then in Program.cs or ServicesInjector.cs:
builder.Services.AddFeatureServices();
Choose the appropriate lifetime for your service:
Lifetime | Description | Use Case |
---|
Singleton | Created once per application | For stateless services that don't depend on request data |
Scoped | Created once per request | For services that maintain state within a request |
Transient | Created each time requested | For lightweight, stateless services |
// Examples
builder.Services.AddSingleton<ISingletonService, SingletonService>();
builder.Services.AddScoped<IScopedService, ScopedService>();
builder.Services.AddTransient<ITransientService, TransientService>();
Inject your service into controllers through constructor injection:
namespace KikiWriting.Controllers;
public class FeatureController : Controller
{
private readonly IFeatureService _featureService;
public FeatureController(IFeatureService featureService)
{
_featureService = featureService;
}
public async Task<IActionResult> Index()
{
var result = await _featureService.DoSomethingAsync(input);
return View(result);
}
[HttpPost]
public IActionResult Process([FromBody] RequestModel model)
{
var result = _featureService.DoSomethingElse(model.Input);
return Json(result);
}
}