Skip to content

Instantly share code, notes, and snippets.

View kasunkv's full-sized avatar
💭
I may be slow to respond.

Kasun Kodagoda kasunkv

💭
I may be slow to respond.
View GitHub Profile
var twoService = ServiceDescriptor.Describe(typeof(ITwoService), typeof(TwoService), ServiceLifetime.Scoped);
services.Add(twoService);
var threeService = ServiceDescriptor.Scoped(typeof(IThreeService), typeof(ThreeService));
services.Add(threeService);
var fourService = ServiceDescriptor.Scoped<IFourService, FourService>();
services.Add(fourService);
services.Replace(ServiceDescriptor.Scoped<IFourService, FourService>());
services.TryAddEnumerable(ServiceDescriptor.Scoped<IThreeService, ThreeService>());
// or
services.TryAddEnumerable(new[] {
ServiceDescriptor.Scoped<IThreeService, ThreeService>(),
ServiceDescriptor.Scoped<IThreeService, AwesomeThreeService>(),
ServiceDescriptor.Scoped<IThreeService, SuperAwesomeThreeService>()
});
@kasunkv
kasunkv / services.cs
Created May 7, 2019 15:49
Register multiple implementations - Method 01
services.AddScoped<IDiscountProcessor, OrderDiscountProcessor>();
services.AddScoped<IDiscount, SeasonalDiscount>();
services.AddScoped<IDiscount, LargeOrderDiscount>();
services.AddScoped<IDiscount, ThreeOrModeDiscount>();
@kasunkv
kasunkv / services.cs
Created May 7, 2019 15:50
Register multiple implementations - Method 02
services.AddScoped<IDiscountProcessor, OrderDiscountProcessor>();
services.TryAddEnumerable(new[]
{
ServiceDescriptor.Scoped<IDiscount, SeasonalDiscount>(),
ServiceDescriptor.Scoped<IDiscount, LargeOrderDiscount>(),
ServiceDescriptor.Scoped<IDiscount, ThreeOrModeDiscount>()
});
public class OrderDiscountProcessor : IDiscountProcessor
{
private readonly IEnumerable<IDiscount> _discounts;
public OrderDiscountProcessor(IEnumerable<IDiscount> discounts)
{
_discounts = discounts;
}
// ...
}
@kasunkv
kasunkv / OrderDiscountProcessor.cs
Created May 7, 2019 15:51
ProcessDiscount() method
public (double, List<string>) ProcessDiscount(OrderViewModel order)
{
var discountDiscroptoons = new List<string>();
var totalDiscount = 0.0;
foreach (var discount in _discounts)
{
var addedDiscount = discount.CalculateDiscount(order);
if (addedDiscount > 0)
{
@kasunkv
kasunkv / services.cs
Created May 12, 2019 14:13
ASP.Net Core Dependency Injection - Implementation Factory
services.AddScoped<IDiscountProcessor, OrderDiscountProcessor>();
services.AddScoped<Discount>(sp =>
{
return new DiscountBuilder()
.WithMinimumBillAmount(1000)
.WithMinimumItemCount(3)
.WithPercentage(10)
.Build();
});