I have the following classes:
public class Foo
{
[Import]
public IFirstInterface firstImport;
[Import]
public ISecondInterface secondImport;
// ...
}
public class A : ISecondInterface {}
public class B : ISecondInterface {}
I would like to able in class Bar, when calling
var foo = compositionContainer.GetExportedValue<Foo>();
To specify wether I want to use class A or B.
I know, I can specify a contract name in the GetExportedvalue method. But as I understand it, this would mean having two class Foo. I would like to reuse the same class but control which class (A or B) is used to satisfy the ISecondInterface dependency.
EDIT :
“What are the rules that will decide whether you use class A or B?”
A:
Foo is called by a wcf service.
Class A and B differ in that they are working on different entities. These entities have different fields and can’t be queried the same way.
My classes are not in english, but I will try to translate to more meaningful terms than Foo and Bar.
Foo could be a RecordAssigner. The RecordAssigner assigns records to users. The logic to do this is contained in this class. The ISecondInterface is an interface to a data layer class that works with records.
It’s implementation expose methods to work on different kinds of records. While both kind of records need can expose the necessary methods for them to be assigned, they are manipulated differently at the data level.
At the service level, I want to be able to have methods called
AssignRecordTypeA and AssignRecordTypeB without duplicating all the code in RecordAssigner.
What are the rules that will decide whether you use class A or B? You can write your own resolver for MEF exports.
This blog post http://randomactsofcoding.blogspot.com/2010/01/configurable-type-catalog-for-mef.html mentions one approach and there are a few other ones that you can find if you search for “mef custom export provider” or “mef custom catalog”
EDIT:
Your scenario reminds me a little bit of a conversation with some colleagues a while ago. In my view MEF is for “extensions” to your application rather than dependencies. The case you have looks more like dependencies. So you would be better off using an IoC container to manage your dependencies. You can have multiple ISecondInterface instances injected in with different keys and then choose which one to use.
If you feel MEF is more suited to your requirements you can still do this by changing
and then deciding which one to use.
Having said that, the case for having one service that deals with two different entities talking to two different repositories is debatable.
If you have some common logic you could refactor that out, but it would be better to have two distinct services each with the dependency it requires to do it’s work.