I thought the whole reason for interfaces, polymorphism, and the pattern, such as Inversion of Control via Injection Dependency Injection, was to avoid tight coupling, separation, modularity, etc.
Why do I need to explicitly "connect" the interface to a specific class, as in ASP.NET? Will my registry have any connection? How,
services.AddTransient<ILogger, DatabaseLogger>();
What if I take logger, ILogger and create a class of files and databases that implement this interface.
In my IoC,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public interface ILogger
{
void logThis(string message);
}
public class DatabaseLogger : ILogger
{
public void logThis(string message)
{
System.Console.WriteLine("inserted into a databse table");
}
}
public class FileLogger : ILogger
{
public void logThis(string message)
{
System.Console.WriteLine("logged via file");
}
}
public class DemoClass
{
public ILogger myLogger;
public DemoClass(ILogger myLogger)
{
this.myLogger = myLogger;
}
public void logThis(string message)
{
this.myLogger.logThis(message);
}
}
class Program
{
static void Main(string[] args)
{
DemoClass myDemo = new DemoClass(new DatabaseLogger());
myDemo.logThis("this is a message");
Console.ReadLine();
}
}
}
So, why should I register or "connect" to something? Isn't that dependency dependency through the constructor (I have a fundamental misunderstanding)? I could place any registrar that implemented ILogger there.
?
services.AddTransient<ILogger, DatabaseLogger>();
services.AddTransient<ILogger, FileLogger>();