Using MEF, let's imagine there is a class called FooType
and I apply the [Export]
attribute on it. Now, I want to import this FooType
somewhere else in my code to use it.
I have tried these two solutions :
[Import]
public FooType Foo { get; set; }
private void MyMethod()
{
Foo.DoSomething();
}
and
private void MyMethod()
{
// _container is of type CompositionContainer and comes from the [ImportingConstructor]
_container.GetExportedValue<FooType>().DoSomething();
}
Both of these worked, the DoSomething()
method of FooType
is correctly called. So it makes me wonder:
An [Import] basically causes MEF to call GetExportedValue and assign it to the property or field. That said, most of the time you don't want your objects to have access to your container. In your second example you said you imported the container itself via ImportingConstructor. I would usually only import FooType via the constructor. I also always prefer constructor injection rather then property injection. It makes the pre-requisites of the object totally clear and your imports can be stored in readonly properties.