So, I'm trying (and seemingly failing) to get my head around DI.
I know that I'm supposed to write my controls/classes so that I pass in the appropriate interfaces and the IoC container will work stuff out for me.
And I can see how this would work for, say, an MVC Controller. I don't instantiate this and the system will inject any dependencies in to it that I include in the constructor.
But what happens further down the chain?
My Controller instantiates a class (ClassA
) that instantiates a class (ClassB
) that needs, say, a Repository.
ATM, I've got code that looks like...
public class ClassB
{
private IMyRepo repo;
public ClassB()
{
repo = DependencyResolver.Current.GetService<IMyRepo>();
// ...
}
}
Now, I'm pretty sure there are going to be gasps in the audience at this, especially as I have to include a reference to System.Web.Mvc at each level of my structure but I'm unsure how else I can do this unless I have something like this ...
public class MyController : MyController
{
private IMyRepo myrepo;
public MyController(IMyRepo myRepo)
{
this.myRepo = myRepo;
}
public ActionResult Index()
{
var classA = new ClassA(myRepo);
classA.DoSomething()
//...
}
}
public class ClassA
{
private IMyRepo repo;
public ClassA(IMyRepo myRepo)
{
this.myRepo = myRepo;
}
public void DoSomething()
{
var classB = new ClassB(myRepo);
// ...
}
}
public class ClassB
{
private IMyRepo repo;
public ClassB(IMyRepo myRepo)
{
this.myRepo = myRepo;
}
}
My problem with this is it means that I'm going to be injecting stuff in to the Controller either directly or via a Factory) that it should't know anything about (the repos in this case) and that feels even more wrong.
I can't resolve how I can use DI properly and at the same time, prevent the necessity of exposing bits of the system where they aren't supposed to be.
I would appreciate any help in understanding the whole DI thing enough that I can solve my dilemma or be able to explain why I can't have my cake and eat it