Search code examples
c#reflectionmef.net-assembly

How to make a "discoverable" service in MEF without a Shared Interface?


Here's the scenario.

Assembly main loads both assembly a and assembly b into the appdomain using MEF. Now lets say that both assembly a and b offer services that can be consumed.

Is it possible for assembly a to invoke/instantiate a class in assembly b at run time, without having a reference? Essentially making services "discoverable"?

I would normally use a shared interface that's referenced by both assemblies, but in this case both assembly a and b don't know about each other until run time.


Solution

  • A shared interface allows the value to be consumed in an early bound (Static Typing) fashion, thanks to Polymorphism, after the appropriate type-cast has been applied. While needing to be common knowledge between parties, a shared interface can also be maintained in an external assembly - this is normally the approach I use.

    There is also Structural Typing (this term is not used in C#/.NET) - basically there is a different interface/type in the consumer that is written so it matches the consumed type. The object in question is accessed in a statically typed manner (through the type defined in the consumer) but functions as a dynamic proxy. See How to make a simple dynamic proxy in C# for details/limitations and some links to implementations.

    However, if neither of the above approaches work then only late binding (Dynamic Typing) can be used - examples are Reflection with object values or dynamic-typed expressions. Some people like it, but I prefer early binding. This is definitely the most "flexible" method.