In this article we are going to discuss Interface Scenarios in Real Applications in C#. There are many blogs, articles are available on the internet regarding Interface Scenarios in Real Applications but in this particular article I will try to explain to you with as much as simple.
Logging: you can define a ILogger interface and have multiple implementations (console, file, database, etc.).
Data Access: Define an interface for data access operations (e.g- IRepository) and create different implementations for different data sources (e.g., SQL, NoSQL, in-memory).
Payment Processing: Define an interface for payment processing (e.g- IPaymentProcessor) and have different implementations for different payment gateways.
Notification Services: Define an interface for notifications (e.g - INotificationService) and have implementations for email, SMS, push notifications, etc.
Logging Scenarios in Real Applications
As below in the example, you can define a ILogger interface and have multiple implementations (console, file, database, etc.).
public interface ILogger
{
void Log(string message);
void LogError(string message);
}
public class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine("Log: " + message);
}
public void LogError(string message)
{
Console.WriteLine("Error: " + message);
}
}
public class FileLogger : ILogger
{
public void Log(string message)
{
// Code to log message to a file
}
public void LogError(string message)
{
// Code to log error to a file
}
}
Use the Interface - Write code that depends on the interface rather than a specific implementation.
public class Application
{
private readonly ILogger _logger;
public Application(ILogger logger)
{
_logger = logger;
}
public void Run()
{
_logger.Log("Application started.");
// Application logic
_logger.LogError("An error occurred.");
}
}
Dependency Injection - You can use dependency injection to pass the appropriate implementation of the interface to your classes.
class Program
{
static void Main(string[] args)
{
ILogger logger = new ConsoleLogger();
Application app = new Application(logger);
app.Run();
}
}