1. Define the Service Interface

Create an interface to define the contract your service will implement.

C#
public interface IMyCustomService
{
    void DoWork();
}

2. Implement the Service

Create a class that implements your service logic.

C#
public class MyCustomService : IMyCustomService
{
    public void DoWork()
    {
        Console.WriteLine("Doing work in MyCustomService...");
    }
}

3. Register the Service in the Dependency Injection (DI) Container

Go to Program.cs and register the service.

C#
var builder = WebApplication.CreateBuilder(args);

// Register service
builder.Services.AddScoped();

var app = builder.Build();

You can use AddSingleton, AddScoped, or AddTransient depending on the lifecycle you need.

AddSingleton – Same instance for the entire app lifetime.
AddScoped – New instance per request.
AddTransient – New instance every time it's requested.

4. Use the Service in a Controller or Class

Inject the service via constructor injection.

C#
public class MyController : ControllerBase
{
    private readonly IMyCustomService _customService;

    public MyController(IMyCustomService customService)
    {
        _customService = customService;
    }

    [HttpGet]
    public IActionResult DoSomething()
    {
        _customService.DoWork();
        return Ok("Work done.");
    }
}