Creating a service in .NET Core (now commonly referred to as .NET) typically means building a reusable class and registering it with the built-in Dependency Injection (DI) system.
Here’s a clean, practical way to do it:
1. Create a Service Interface
Define a contract for your service.
public interface IEmailService
{
string SendEmail(string to, string message);
}
2. Implement the Service
Create a class that implements the interface.
public class EmailService : IEmailService
{
public string SendEmail(string to, string message)
{
// Simulate email sending
return $"Email sent to {to} with message: {message}";
}
}
3. Register the Service in DI Container
In Program.cs (for .NET 6+):
var builder = WebApplication.CreateBuilder(args);
// Register service
builder.Services.AddScoped<IEmailService, EmailService>();
var app = builder.Build();
Service Lifetimes:
AddTransient → New instance every time
AddScoped → One per request
AddSingleton → Single instance for entire app
4. Use the Service in Controller
public class HomeController : Controller
{
private readonly IEmailService _emailService;
public HomeController(IEmailService emailService)
{
_emailService = emailService;
}
public IActionResult Index()
{
var result = _emailService.SendEmail("test@mail.com", "Hello!");
return Content(result);
}
}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Creating a service in .NET Core (now commonly referred to as .NET) typically means building a reusable class and registering it with the built-in Dependency Injection (DI) system.
Here’s a clean, practical way to do it:
1. Create a Service Interface
Define a contract for your service.
2. Implement the Service
Create a class that implements the interface.
3. Register the Service in DI Container
In Program.cs (for .NET 6+):
Service Lifetimes:
AddTransient→ New instance every timeAddScoped→ One per requestAddSingleton→ Single instance for entire app4. Use the Service in Controller
5. (Optional) Use in Minimal API
Key Concept
This uses Dependency Injection, which is a core concept in ASP.NET Core. It helps:
Pro Tips (Production Level)
Since you're working on large-scale systems:
ILogger<T>