Is having a wrapper for your IoC a good idea?

≡放荡痞女 提交于 2019-12-06 05:19:05

For this reason the Common Service Locator project has been developed. It is an abstraction over DI frameworks and it defines an interface much like your IoC class. I even developed the Simple Service Locator library; an DI library that is a direct implementation of the Common Service Locator interface.

So in that sense, it's not weird to have an abstraction over DI frameworks. However, when doing Dependency Injection correctly (and completely), the idea is to adjust the design of your application accordingly, configure the container in the application root, and have preferably just a single place in the application were types are assembled (read: were GetInstance is called). For an ASP.NET MVC application, this would be the ControllerFactory. For ASP.NET WebForms application you would typically need to override a PageHandlerFactory.

When you play by these rules, there is no reason to use such an abstraction, because you just call the container at a single place in your application anyway. However, if that's not feasible for you, using either the Common Service Locator or your own abstraction is an alternative.

But please take a step back before you decide to let your code depend on an abstraction over your IoC library, because this causes a lot of problems and is seen as an anti-pattern in general. Calling back into the container from within your code:

  • Makes the code much harder to test.
  • Hides dependencies instead making the code harder to read and maintain.
  • Disables compile-time support.
  • Disallows your dependency graphs to be verified by a tool.

If you have a lot of libraries and a lot of applications built on top of those libraries you'll end up with a large amount of IoC registration code which gets duplicated across all of those applications.

You could have each library responsible for registering itself with a container but then it has to know about a specific IoC implementation. Or you could do as you suggest and create an IoC wrapper and have your libraries responsible for registering themselves via the IoC wrapper.

Jaguir

The pro is that you can swap IOC containers painlessly. The con is that you lose any functionality specific to an IOC container. MVC turbine uses this approach. Have a look at it's source to see how it handles the locator. http://mvcturbine.codeplex.com/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!