Register dependencies via reflection + Autofac module

register dependency

Imagine that you have ten or hundred class in your repository. And now you need to register each of them. Do you want to do it this way?

Very tedious work, whenever you add some class you need to again register that dependency. Instead of that you can use reflection + Autofac module and automatically register all class that have „marker” interface.

Example

Create a marker to all your (e.g) repository interfaces.

Mark all interfaces belonging to the repositories with IRepository marker.

Now you have all what is need to register all repository at once.

To make that I’ll use for it IoC container Autofac but it can be some other if you prefer.

So at first, let’s make module that will register all repositories via reflection.

This class will inherit after Autofac.Module and override function Load to register all dependencies on my current assembly which register all interfaces with the mark interface IRepository as a single instance.

At this point I can analogously do for other modules, for example, services or handlers.

Then create a container to register all modules which you have.

And now you only need to modify the start-up class in order for the modules to register properly.

That’s end, we can now enjoy that the containers automatically register the dependencies that are marked with appropriate markers.

Let’s Make Life Easier

 

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *