How Do I Create a Custom Service in .NET Core?
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Amit MohantyRank #112 · 20K reputationPosted May 19, 2025, 1:29 AM EDT
1. Define the Service Interface
Create an interface to define the contract your service will implement.
public interface IMyCustomService { void DoWork(); }2. Implement the Service
Create a class that implements your service logic.
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.
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.
public class MyController : ControllerBase { private readonly IMyCustomService _customService; public MyController(IMyCustomService customService) { _customService = customService; } [HttpGet] public IActionResult DoSomething() { _customService.DoWork(); return Ok("Work done."); } }