Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shall I pass Dependency Injection Container (DIC) as parameter in MVC?

I am currently writing my own MVC framework for learning purpose and I decided to use a Dependency Injection Container to share common used objects between classes (for example DB instance).

I initialized the container in my bootstrap file and I have a instance of it in my Application class, is it a good practice to pass an instance of the container during the routing process? (i.e. passing container object as a parameter in ControllerBase constructor). Also, is it good practice to accept the container as a parameter in the constructor of my ModelBase?

like image 602
user1365914 Avatar asked Feb 11 '15 17:02

user1365914


1 Answers

It sounds as a Dependency Injector is something different to what you are doing. It sounds more like a ServiceLocator, a repository or whatever. Usually the Dependency Injector is inbetween the call (if you use it for parameter injection) or between the creation (if you use it for field or constructor injection).

The usage of the dependency injector must be completely transparent to the code/object being injected to. So if you pass a reference you do something wrong.

Also the DependencyInjector belongs to the environment your code runs within. See it as it is. The dependency injector should even not be known to the application unless you use the application as being the framework you run in.

So get dependency injection to work means no reference to the injector within the actual application. The goal is to run the application both way with injection or without. Periode.

like image 134
Martin Kersten Avatar answered Oct 17 '22 03:10

Martin Kersten