.Net Core dependency injection multiple implementations

In this series, I will discuss how to register multiple implementations of a service interface.

Let’s assume you are developing one application in which you want to validate the customer information like Age and Email.

As you can see in the class diagram that there is one interface, IValidator, and there are two classes that implement it are EmailValidator and AgeValidator.

public class Customer
{
	public int Id { get; set; }
	public int Age { get; set; }
	public string Email { get; set; }
}
public interface IValidator
{
	bool Validate(Customer customer);
}
public class AgeValidator : IValidator
{
	private readonly ILogger _logger;

	public AgeValidator(ILogger<AgeValidator> logger)
	{
		_logger = logger;

	}

	public bool Validate(Customer customer)
	{
		_logger.LogInformation($"Validating customer Age {customer.Age}");
		return true;
	}
}
public class EmailValidator : IValidator
{
	private readonly ILogger<EmailValidator> _logger;

	public EmailValidator(ILoggerFactory loggerFactory)
	{
		_logger = loggerFactory.CreateLogger<EmailValidator>();

	}

	public bool Validate(Customer customer)
	{
		_logger.LogInformation($"Validating customer Email {customer.Email}");
		return true;
	}
}

Now it’s time to use these classes in our customer service.

public interface ICustomerService
{
	bool Validate(Customer customer);

}
public class CustomerService : ICustomerService
{
	private readonly IEnumerable<IValidator> _validators;
	public CustomerService(IEnumerable<IValidator> validators)
	{
		_validators = validators;
	}

	public bool Validate(Customer customer)
	{

		var isValid = false;
		foreach (var element in _validators)
		{
			isValid = element.Validate(customer);
		}
		return isValid;
	}
}

Register the dependency

public class Startup
{


	public static ServiceProvider Configure()
	{
		var provider = new ServiceCollection()
					.AddSingleton<ICustomerService, CustomerService>()
					.AddSingleton<IValidator, AgeValidator>()
					.AddSingleton<IValidator, EmailValidator>()
					.AddLogging(fs => fs.AddConsole())
					.BuildServiceProvider(validateScopes: true);
		return provider;
	}

}
void Main()
{
	var container = Startup.Configure();
	var customerService = container.GetService<ICustomerService>();
	customerService.Validate(new Customer() { Age = 21, Email = "john@doe.com" });

}

Output

info: AgeValidator[0]  
Validating customer Age 21  
info: EmailValidator[0]  
Validating customer Email john@doe.com

إرسال تعليق

Please do not post any spam link in the comment box😊

أحدث أقدم

Blog ads

CodeGuru