Interfaces and dependency injection

To avoid dependencies on a specific service implementation, you can instead configure a service for a specific interface and then depend just on the interface. This approach gives you the flexibility to swap out the service implementation, which makes the code more testable and easier to maintain.

Consider an interface for the PersonService class:

C#Copy

public interface IPersonService
{
    string GetPersonName();
}

This interface defines the single method, GetPersonName, that returns a string. This PersonService class implements the IPersonService interface:

C#Copy

internal sealed class PersonService : IPersonService
{
    public string GetPersonName()
    {
        return "John Doe";
    }
}

Instead of registering the PersonService class directly, you can register it as an implementation of the IPersonService interface:

C#Copy

var builder = WebApplication.CreateBuilder(args);
    
builder.Services.AddSingleton<IPersonService, PersonService>();
var app = builder.Build();

app.MapGet("/", 
    (IPersonService personService) => 
    {
        return $"Hello, {personService.GetPersonName()}!";
    }
);
    
app.Run();
contact

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *