Introduction
Here I will show you how we can register and use multiple classes implementing same interface when Autofac is used as dependencies registrar.
Background
If multiple classes implementing same interface, then how we can get the desired implementation in our business class while using Autofac as dependencies registrar? This is issue which needs to be handle.
Lets say we have one interface:
public interface ICake
{
decimal GetPrice();
}
And two classes implementing this interface.
First Class:
public class PlainCake : ICake
{
public PlainCake()
{
}
public decimal GetPrice()
{
return 30.45M;
}
}
Second Class:
public class FruitCake : ICake
{
public FruitCake()
{
}
public decimal GetPrice()
{
return 50.8M;
}
}
In dependencies registrar we register our classes with interface like this:
builder.RegisterType<PlainCake>().As<ICake>().InstancePerRequest();
builder.RegisterType<FruitCake>().As<ICake>().InstancePerRequest();
Now in our business class we create an object like this:
private readonly ICake _Cake;
Now, here how we can get the GetPrice method implementation of PlainCake
class and FruitCake
class with this object???
Using the Code
Here is a work around and we can handle such situations with little bit decorating our interface like this:
Now our interface will look like this:
public interface ICake<T> where T : class
{
decimal GetPrice();
}
and our classes will look like this:
First Class:
public class PlainCake : ICake<PlainCake>
{
public PlainCake()
{
}
public decimal GetPrice()
{
return 30.45M;
}
}
Second Class:
public class FruitCake : ICake<FruitCake>
{
public FruitCake()
{
}
public decimal GetPrice()
{
return 50.8M;
}
}
In dependencies registrar we can register them like this:
builder.RegisterType<PlainCake>().As<ICake<PlainCake>>().InstancePerRequest();
builder.RegisterType<FruitCake>().As<ICake<FruitCake>>().InstancePerRequest();
In our business class we can call them like this:
private readonly ICake<PlainCake> _plainCake;
private readonly ICake<FruitCake> _fruitCake;
public EvaluationBusiness(ICake<PlainCake> plaincake, ICake<FruitCake> fruitCake)
{
_plainCake = plaincake;
_fruitCake = fruitCake;
}
and calling GetPrice
method.
var _plainCakePrice = _plainCake.GetPrice();
var _fruitCakePrice = _fruitCake.GetPrice();
It is my implementation to handle such situation. (Our goal was not to reduce the number of lines of code). There will be a lot of solutions to handle such situations and hope so you will be handling this situation too with some fixes.
I hope it will help someone or someone have more better solutions to handle such situations.