Are you building scalable, testable applications in ASP.NET Core?
Then you must embrace the ๐๐ฒ๐ฝ๐ฒ๐ป๐ฑ๐ฒ๐ป๐ฐ๐ ๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ผ๐ป ๐ฃ๐ฟ๐ถ๐ป๐ฐ๐ถ๐ฝ๐น๐ฒ (๐๐๐ฃ) and implement it using ๐๐ฒ๐ฝ๐ฒ๐ป๐ฑ๐ฒ๐ป๐ฐ๐ ๐๐ป๐ท๐ฒ๐ฐ๐๐ถ๐ผ๐ป (๐๐).
Hereโs a simple, clear example to help you understand how both work together in a real ASP.NET Core project. ๐
๐น Step 1: Define an Interface and Implementation (DIP)
public interface IMessageService
{
string GetMessage();
}
public class HelloMessageService : IMessageService
{
public string GetMessage()
{
return "Hello from the message service!";
}
}
๐ก Your controller now depends on an abstraction (interface) โ this is ๐๐ฒ๐ฝ๐ฒ๐ป๐ฑ๐ฒ๐ป๐ฐ๐ ๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ผ๐ป ๐ฃ๐ฟ๐ถ๐ป๐ฐ๐ถ๐ฝ๐น๐ฒ in action.
๐ธ Step 2: Inject the Dependency into the Controller (DI)
public class MessageController : ControllerBase
{
private readonly IMessageService _messageService;
public MessageController(IMessageService messageService)
{
_messageService = messageService;
}
public IActionResult Get()
{
return Ok(_messageService.GetMessage());
}
}
This is ๐ฐ๐ผ๐ป๐๐๐ฟ๐๐ฐ๐๐ผ๐ฟ ๐ถ๐ป๐ท๐ฒ๐ฐ๐๐ถ๐ผ๐ป, one of the most common forms of ๐๐ฒ๐ฝ๐ฒ๐ป๐ฑ๐ฒ๐ป๐ฐ๐ ๐๐ป๐ท๐ฒ๐ฐ๐๐ถ๐ผ๐ป in ASP.NET Core.
๐น Step 3: Register the Service in Program.cs
builder.Services.AddScoped();
Now your service is automatically injected by the .๐ก๐๐ง ๐๐ผ๐ฟ๐ฒ ๐ฏ๐๐ถ๐น๐-๐ถ๐ป ๐๐ ๐ฐ๐ผ๐ป๐๐ฎ๐ถ๐ป๐ฒ๐ฟ.
When /message
is called, the controller gets its dependency injected from the container. No tight coupling. Easy to test. Clean architecture. ๐ช
๐ฌ ๐๐ฎ๐๐ฒ ๐๐ผ๐ ๐ถ๐บ๐ฝ๐น๐ฒ๐บ๐ฒ๐ป๐๐ฒ๐ฑ ๐บ๐๐น๐๐ถ๐ฝ๐น๐ฒ ๐๐ฒ๐ฟ๐๐ถ๐ฐ๐ฒ ๐ถ๐บ๐ฝ๐น๐ฒ๐บ๐ฒ๐ป๐๐ฎ๐๐ถ๐ผ๐ป๐ ๐ผ๐ฟ ๐๐๐ฒ๐ฑ ๐บ๐ผ๐ฐ๐ธ ๐๐ฒ๐ฟ๐๐ถ๐ฐ๐ฒ๐ ๐ณ๐ผ๐ฟ ๐๐ฒ๐๐๐ถ๐ป๐ด ๐๐ถ๐๐ต ๐๐ ๐ถ๐ป ๐๐ผ๐๐ฟ ๐ฝ๐ฟ๐ผ๐ท๐ฒ๐ฐ๐? ๐ช๐ผ๐๐น๐ฑ ๐น๐ผ๐๐ฒ ๐๐ผ ๐ต๐ฒ๐ฎ๐ฟ ๐ต๐ผ๐ ๐๐ผ๐ ๐๐๐ฟ๐๐ฐ๐๐๐ฟ๐ฒ๐ฑ ๐ถ๐! ๐