How to hide the real IoC container library?

I want to extract all of my code from the IoC container library that I selected (Unity). To do this, I created the IContainer interface, which provides the functions Register () and Resolve (). I created a class called UnityContainerAdapter that implements IContainer and which wraps a real container. Thus, only the assembly in which the UnityContainerAdapter is defined knows about the Unity library.

I have a leak in my isolation. Unity looks for attributes for type members to know where to inject the dependencies. Most of the IoC libraries I've seen also support this. The problem with me is that I want to use this function, but I do not want my classes to depend on a specific Unity attribute.

Do you have any suggestions to fix this problem?

Ideally, I would create my own [Dependency] attribute and use it in my code. But I would have to tell the real container to search for my attribute instead of its own.

+4
source share
3 answers

I found the answer: Unity uses the extension to configure what they call "selector policies." To replace the attributes used by Unity, you simply encode your own version of the UnityDefaultStrategiesExtension class and register your own selector policies that use your own attributes.

For more information on how to do this, see this post on the Unity codeplex website.

I'm not sure it will be easy to do the same if I switch to another IoC library, but now this solves my problem.

+3
source

Browse the Common Service Locator Project :

The shared services locator library contains a common interface for the location of the service, the application and infrastructure developers can reference. The library provides abstraction through containers and the maintenance of IoC locators. Using the library allows the application to indirectly access features without relying on Recommendations. We hope that using this library, third-party applications and frameworks can begin to use the IoC / Location services without binding themselves to a specific implementation.


Edit: this does not seem to solve your desire to use an attribute-based dependency declaration. You can either not use it or find a way to abstract the attributes for several injection libraries (for example, you mentioned).

This is the main problem with declarative interfaces - they are tied to a specific implementation.

Personally, I stick with the design injection, so I do not run into this problem.

+4
source

Unable to configure configuration without attributes in xml. This makes it a little more "obscure", I know, I personally use a combination of xml and attributes, but at least it "solves" your dependence on unity.

0
source

All Articles