Introduction
In the previous lesson, we implemented CRUD operations and discussed where the repository approach belongs in an application. As controllers begin to handle slug generation, publishing, title normalization, and configuration values in addition to data access, they quickly become difficult to maintain.
In this lesson, we will move business rules out of controllers and into a service layer. We will define services through interfaces, register them with ASP.NET Core’s Dependency Injection container, and read content-related settings through strongly typed options.
Our example assumes a content management application with an administration area. When a content item is created, a slug will be generated from its title. When it is published, a publication date will be assigned. These rules will be owned by the service rather than by the controller.
What is Dependency Injection?
Dependency Injection means that a class receives the objects it needs instead of creating those objects internally. Rather than writing new ContentService() inside a controller, the service is provided through the controller’s constructor.
This approach provides three important benefits:
- Loose coupling: The controller depends on an interface rather than the implementation details of a concrete class.
- Testability: A fake or mock service can be supplied during testing.
- Centralized lifetime management: ASP.NET Core controls when service instances are created and disposed.
In ASP.NET Core, services are usually registered through builder.Services. The most common service lifetimes are:
| Lifetime | Description | Typical use |
|---|---|---|
Transient | A new instance is created each time it is requested. | Small stateless helper services |
Scoped | One instance is created for each HTTP request. | Application services that use DbContext |
Singleton | One instance is used for the lifetime of the application. | Shared, thread-safe, stable services |
Because Entity Framework Core’s DbContext is commonly scoped, application services that depend on it are generally registered as scoped as well.
Defining the service contract
First, let’s define the operations that the content service exposes. The interface represents the minimum contract that a controller needs to know about.
using BlogApp.Models;
namespace BlogApp.Services;
public interface IContentService
{
Task<Content> CreateAsync(Content content, CancellationToken cancellationToken = default);
Task<bool> PublishAsync(int id, CancellationToken cancellationToken = default);
string CreateSlug(string title);
}For this example, assume that Content is the entity created in earlier lessons. If your entity has a different name, replace the type in the interface with the model used by your project.
Notice that the method names describe business operations. The controller should not need to know that publishing means loading an entity, setting a Boolean value, assigning a date, and saving changes. It should simply be able to request that the content be published.
Implementing the service layer
Now create a class that implements the interface. The service will use both ApplicationDbContext and options that control slug behavior.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using BlogApp.Data;
using BlogApp.Models;
namespace BlogApp.Services;
public sealed class ContentService(
ApplicationDbContext dbContext,
IOptions<ContentOptions> options) : IContentService
{
private readonly ApplicationDbContext _dbContext = dbContext;
private readonly ContentOptions _options = options.Value;
public async Task<Content> CreateAsync(
Content content,
CancellationToken cancellationToken = default)
{
content.Slug = CreateSlug(content.Title);
content.CreatedAt = DateTime.UtcNow;
_dbContext.Contents.Add(content);
await _dbContext.SaveChangesAsync(cancellationToken);
return content;
}
public async Task<bool> PublishAsync(
int id,
CancellationToken cancellationToken = default)
{
var content = await _dbContext.Contents
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
if (content is null)
{
return false;
}
content.IsPublished = true;
content.PublishedAt ??= DateTime.UtcNow;
await _dbContext.SaveChangesAsync(cancellationToken);
return true;
}
public string CreateSlug(string title)
{
var slug = title.Trim().ToLowerInvariant();
foreach (var character in _options.RemovableCharacters)
{
slug = slug.Replace(character.ToString(), string.Empty);
}
slug = string.Join('-', slug
.Split(' ', StringSplitOptions.RemoveEmptyEntries));
return slug;
}
}The service now centralizes three business rules:
- A slug is generated for new content.
- The creation time is assigned in UTC.
- Publishing only succeeds when the content exists, and an existing publication date is preserved.
Using DateTime.UtcNow reduces dependence on the server’s local time zone. If a user-specific time zone is required, conversion can be performed when the value is displayed.
Making slug generation more reliable
A simple Replace-based implementation is sufficient for demonstrating the architecture, but a production application should also consider Turkish characters, punctuation, repeated whitespace, and duplicate titles. For example, two different titles may produce the same slug after normalization.
A robust slug process can be divided into these steps:
- Trim leading and trailing whitespace.
- Convert the title to lowercase.
- Normalize or preserve accented characters according to the application’s SEO policy.
- Remove unsupported characters.
- Convert whitespace to hyphens.
- Add a unique suffix when the slug already exists.
Slug uniqueness should be designed together with the database layer. An application-only check can still allow a race condition when two requests run at the same time. For that reason, add a unique index to the slug column and handle a conflict in a controlled way.
Using the options pattern for configuration
Instead of hard-coding slug behavior in the service, make it configurable through appsettings.json.
{
"Content": {
"RemovableCharacters": [".", ",", "!", "?", ":", ";", "'", "\""],
"MaxTitleLength": 180
}
}Create a strongly typed options class for this section:
namespace BlogApp.Services;
public sealed class ContentOptions
{
public const string SectionName = "Content";
public string[] RemovableCharacters { get; set; } = [];
public int MaxTitleLength { get; set; } = 180;
}Bind the configuration section in Program.cs:
using BlogApp.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationDbContext>(...);
builder.Services
.AddOptions<ContentOptions>()
.Bind(builder.Configuration.GetSection(ContentOptions.SectionName))
.Validate(options => options.MaxTitleLength > 0,
"MaxTitleLength must be greater than zero.")
.ValidateOnStart();
builder.Services.AddScoped<IContentService, ContentService>();
var app = builder.Build();The options pattern binds related settings to a strongly typed class. The service no longer needs to read every value as a string from IConfiguration or perform manual conversions. With ValidateOnStart, invalid configuration is detected while the application starts.
Environment-specific settings can be stored in appsettings.Development.json, appsettings.Production.json, or environment variables. Secrets, passwords, and connection strings should not be committed to source control. Use an appropriate local secret store during development and a secure secret-management solution in production.
Using the service in a controller
The controller no longer needs to implement data access and business rules itself:
using Microsoft.AspNetCore.Mvc;
using BlogApp.Models;
using BlogApp.Services;
namespace BlogApp.Controllers;
public class ContentsController(IContentService contentService) : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(
Content content,
CancellationToken cancellationToken)
{
if (!ModelState.IsValid)
{
return View(content);
}
var createdContent = await contentService.CreateAsync(
content, cancellationToken);
return RedirectToAction(nameof(Details),
new { id = createdContent.Id });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Publish(
int id,
CancellationToken cancellationToken)
{
var published = await contentService.PublishAsync(
id, cancellationToken);
if (!published)
{
return NotFound();
}
return RedirectToAction(nameof(Index));
}
}The controller is now easier to read. It handles model validation and HTTP results, while slug generation, date assignment, and persistence remain in the service layer.
Registration and service lifetimes
The registration AddScoped<IContentService, ContentService> creates one service instance per HTTP request. This is appropriate because the service depends on a scoped DbContext.
Injecting a scoped service such as ApplicationDbContext directly into a singleton service creates a lifetime mismatch. Singleton services must not retain request-specific data or shorter-lived dependencies. Also, prefer constructor injection over manually calling GetService from the service container. Constructor injection makes dependencies visible and allows missing registrations to fail early.
Common mistakes
- Leaving business rules in controllers: Repeated rules can diverge when they are implemented in several actions.
- Depending on concrete classes: Injecting
IContentServiceinstead ofContentServiceimproves flexibility and testability. - Choosing the wrong lifetime: Services that use DbContext are commonly registered as scoped.
- Reading configuration as strings everywhere: Options classes improve naming, conversion, and validation.
- Checking slug uniqueness only in application code: Add a database unique index and handle conflicts as well.
- Using local server time: Servers may run in different time zones. Storing timestamps in UTC is more consistent.
- Creating one oversized service: Separate content management, email delivery, file processing, and other distinct responsibilities when necessary.
Short practice exercise
Complete the following exercise:
- Add a
DefaultAuthorproperty toContentOptions. - Configure the value in
appsettings.json. - Assign the default author in
CreateAsyncwhen the submitted author is empty. - Improve
CreateSlugso that repeated hyphens are reduced to one hyphen. - Create two content items with the same title and test the uniqueness behavior.
- Create a simple test double for
IContentServiceand observe how the controller can be tested without a real database.
Conclusion
In this lesson, we separated controllers from business rules. We defined a service contract with an interface, centralized content creation and publishing behavior in ContentService, and registered the implementation through Dependency Injection.
We also used the ContentOptions class to read and validate configuration through strongly typed options. This structure will help keep the application maintainable as we add authentication, authorization, file uploads, SEO features, or email notifications in later lessons. The next step is to apply security and authorization rules within this service-oriented design.