Multiple Implementation of Interface in ASP.net core

This approach utilizes the new feature default interface methods introduced in C# 8.0, so we will need .NET Core 3.x or newer versions to implement this approach.

Let’s say we have the following interface:

 public interface IPayment
    {
        string Pay();
    }

This interface has multiple implementations with two different classes, Visa and Master:

public class Master : IPayment
    {
        public string Pay()
        {
            return "Master payment";
        }
    }
  public class Visa : IPayment
    {
        public string Pay()
        {
            return "Visa payment";
        }
      
    }

The services registered as the following:

 services.AddScoped<IPayment,Visa>();
 services.AddScoped<IPayment, Master>();


For the sake of simplicity, we will resolve the service inside MVC action method:

 public IActionResult Index()
 {
   var payment = HttpContext.RequestServices
                .GetService<IPayment>();
   var data = payment.Pay();
   return Content(data);
 }

The result will be the implementation of the Master class because it’s the last class registered for the same interface, to be able to decide which class to resolve, we can use default interface implementation like this:

 public interface IPayment
    {
        string Pay();
        public bool IsVisa { get => false; }
    }
 public class Visa : IPayment
    {
        public string Pay()
        {
            return "Visa payment";
        }
        public bool IsVisa { get => true; }
    }

We have added IsVisa property to decide if we want to implement the code in the Visa class instead of the Master class, this value will be used for interface conditional resolving:

public IActionResult Index()
 {
    var payment = 
            HttpContext.RequestServices
           .GetServices<IPayment>()
           .First(x=>x.IsVisa);

   var data = payment.Pay();
   return Content(data);
 }


This code will resolve the IPayment interface depending on the value of IsVisa, in more complex scenarios, we can use enums or strings to select the implementation we want in the run time.

Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s