Unity container dependency not resolved

Sep 17, 2010 at 10:25 PM
Edited Sep 17, 2010 at 10:31 PM

I am extending our system which is currently using Unity with MEF and Unity integration provided by MEF Contrib. Now, I have discovered an interesting problem. Most of the classes in our system look like this:

public class Service : IService
    public IUnityContainer Container { get; set; }


When this class is manually registered in Unity, after it is resolved, the Container property is properly set. However, when MEF is used together with Unity integration instead of manual registration, the class is properly resolved by Unity but the Container property is not set and remains null. I have even tried to explicitly self-register the Unity container instance, but it did not help. Has anyone already observed such behaviour and knows how to overcome this issue?


Sep 19, 2010 at 11:52 AM

When designing classes for use with both Unity and MEF, you have to be very careful. You have to be aware of who owns how concept, as the integration layer uses dual container approach. By this I mean You have to be sure which container creates the instance, thus you have to use container specific set of attributes. In your particular example, the Service class is created by MEF, and MEF knows nothing about the Dependency attribute. However, it knows about the Import attribute, so to fix you class, swap the Dependecy attribute with the Import attribute and everything will work as expected. Please note, that when an instance is created by the Unity container, it will properly inject dependencies marked with Unity and MEF specific attributes, because after Unity creates the instance, it runs the composition on it.

To sum up, the general rule of thumb is as follows: When the instance is created by MEF, use only MEF specific attributes. When the instance is created by Unity, you are free to use both Unity's and MEF's attributes. 

Hope this helps!