Hi this might be trivial but I am trying to understand the class instantiation using interface. So below is my code:
public interface IRepository
{
string GetMemberDisplayName();
}
public class Repository : IRepository
{
private readonly Manager _manager;
public Repository() {}
public Repository(string connectionName)
{
_manager = new Manager(connectionName);
}
public string GetMemberDisplayName(string ID)
{
return "FooFoo";
}
}
Now in another class that uses the repository class functionality has instantiated it as follows:
public class LogServiceHelper
{
readonly IRepository _alrAttendance;
readonly IRepository _alrUsers;
public LogServiceHelper()
{
_alrAttendance = new Repository("value1");
_alrUsers = new Repository("value2");
}
public string GetMemberName(string empId)
{
return _alrUsers.GetMemberDisplayName(empId);
}
}
My question is if this is correct way to instantiate a class with parameterized constructor. And if yes, then second question is why do we need interface in this case. We could directly instantiate the class without creating the interface?
Yes, that's how to invoke a parameterized constructor, but no, that's not what you should be doing.
As you have it,
LogServiceHelper
has a hard dependency on theRepository
class, and so you are right, the interfaces don't buy you anything. However, if they were injected:You suddenly gain the benefits of abstraction. Notably that a unit test could pass in fake repositories, and that you can switch to another implementation of
IRepository
without changingLogServiceHelper
.The next question is then "Who creates the
Repository
concrete class?". For that, I refer you to the variety of DI/IoC containers out there, such as Autofac, Unity, and NInject.