I am reading this article about using DI inside ASP.NET Core @ https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-6.0 .. but i can not understand its benefit of providing abstraction level.
for example without DI, we will have those classes:-
public class MyDependency
{
public void WriteMessage(string message)
{
Console.WriteLine($"MyDependency.WriteMessage called. Message: {message}");
}
}
public class IndexModel : PageModel
{
private readonly MyDependency _dependency = new MyDependency();
public void OnGet()
{
_dependency.WriteMessage("IndexModel.OnGet");
}
}
and with DI we will have those classes:-
public interface IMyDependency
{
void WriteMessage(string message);
}
public class MyDependency : IMyDependency
{
public void WriteMessage(string message)
{
Console.WriteLine($"MyDependency.WriteMessage Message: {message}");
}
}
public class Index2Model : PageModel
{
private readonly IMyDependency _myDependency;
public Index2Model(IMyDependency myDependency)
{
_myDependency = myDependency;
}
public void OnGet()
{
_myDependency.WriteMessage("Index2Model.OnGet");
}
}
but at the end with DI or without DI if i want to modify the WriteMessage method, to accept 2 strings instead of one as follow:-
public void WriteMessage(string message,string message2)
{
Console.WriteLine($"MyDependency.WriteMessage called. Message: {message}{message2}");
}
i will have to modify the related classes; without DI case:-
public class IndexModel : PageModel
{
private readonly MyDependency _dependency = new MyDependency();
public void OnGet()
{
_dependency.WriteMessage("IndexModel.OnGet","two");
}
}
with DI case:-
public class Index2Model : PageModel
{
private readonly IMyDependency _myDependency;
public Index2Model(IMyDependency myDependency)
{
_myDependency = myDependency;
}
public void OnGet()
{
_myDependency.WriteMessage("Index2Model.OnGet","two");
}
}
so not sure how using DI will create an abstraction between the WriteMessage
implementation and the classes which consume it.. or i am understanding DI and its benefits wrongly?
Thanks