简体   繁体   中英

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? (ie 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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM