Skip to main content

Posts

Showing posts with the label dependency injection

Dependency Injection In .NET Core With Strategy Pattern

In the previous post, we gave an introduction and explained the basic concept of the  Strategy Pattern . Now, we want to go a bit further and demonstrate how it works in practice alongside a dependency injection in .NET Core. Instead of manually instantiating strategies, we let the ASP.NET Core DI container inject the correct implementation at runtime. Example For the showing purposes, let us asume that we are implementing some payment service, and we want to use one service at the time, depending on user input. For our strategy pattern, we would need following components: Interface public interface IPaymentStrategy { void Pay ( decimal amount ) ; } Concrete Strategies public class CreditCardPayment : IPaymentStrategy { public void Pay(decimal amount) { Console.WriteLine($"Paid ${amount} using Credit Card."); } } public class PayPalPayment : IPaymentStrategy { public void Pay(decimal amount) { Console.WriteLine($"Paid ${amoun...