Registering the Repository in the DI Container

Right, the magic of Dependency Injection containers. Let’s start small by registering our MockRepository against the IRepository<ToDoItem> interface, and using the DI container to retrieve it in our View.

I’m going to register the interface inside the App’s constructor. This is cross-platform, so it’s the constructor inside the .NET Standard library, not the platform-specific projects.

This tells my DI container to give me an instance of my MockRepository class every time I ask for an IRepository<ToDoItem>. Since that’s exactly what I need for my View, I can change that to:

as a First step. Go and set a breakpoint where you retrieve the repo from the DI container, and you’ll see that you get an instance of a MockRepository when you ask for an IRepository<ToDoItem>.

The most important thing here is that the View is now decoupled from the MockRepository, i.e. it doesn’t decide which concrete class should be used as a repository. That means that when, later on, we want to use a real repository instead of our mockup, we only have to change the registration in our App’s constructor, rather than having to hunt down every line where we’re creating a new instance of a class that takes an IRepository as a constructor argument.

That said, this can still be improved upon – more on that in the next post.

Leave a Reply

Your email address will not be published. Required fields are marked *