transient, scoped, and singleton
// IProductCatalogService.cs
public interface IProductCatalogService {
List GetProducts();
}
// IShoppingCartService.cs
public interface IShoppingCartService {
void AddToCart(Product product);
List GetCartItems();
}
// IOrderProcessingService.cs
public interface IOrderProcessingService {
void ProcessOrder(List cartItems);
}
// ProductCatalogService.cs
public class ProductCatalogService : IProductCatalogService {
public List GetProducts() {
// Fetch products from a database or external API
// For simplicity, returning sample data here
return new List { new Product { Id = 1, Name = "Product 1", Price = 10.99 }, new Product { Id = 2, Name = "Product 2", Price = 19.99 },
// ... other products
}; } }
// ShoppingCartService.cs
public class ShoppingCartService : IShoppingCartService {
private List _cartItems = new List();
public void AddToCart(Product product) {
_cartItems.Add(product);
}
public List GetCartItems() {
return _cartItems;
} }
// OrderProcessingService.cs
public class OrderProcessingService : IOrderProcessingService {
public void ProcessOrder(List cartItems) {
// Perform order processing, payment, etc.
// For simplicity, printing order details here Console.WriteLine("Processing order with items:");
foreach (var item in cartItems) {
Console.WriteLine($" - {item.Name}, Price: {item.Price:C}");
} Console.WriteLine("Order processed successfully.");
}
}