0

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.

Jester
  • 56,577
  • 4
  • 81
  • 125
Matt
  • 6,264
  • 10
  • 54
  • 82

2 Answers2

1

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.

Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220
0

Here's my take on this:

you only NEED one interface for MEF to work. Wow, you really don't even need that, you could resolve a named contract of type object that returns an object and that object can do whatever it wants like resolve other dependencies via MEF with contracts in their OWN libraries.

[Import("MyEntryDelegate",typeof(object))]
public Lazy<object> mefBootstrapper { get; set; }

you have an object resolved by MEF for one common known interface and all other MEF resolved objects will discover their own parts in the external dlls loaded in the catalogs. Like shake and bake IoC, write your own interfaces in your library and [Import] the dependencies to your hearts content

In the constructor of whatever object you are creating, you can bootstrap whatever you want.

interface INeedSomethingOfMyOwn{
    void DoSomething();
}
[Export("MyEntryDelegate",typeof(object))]
class MyClass{
    private readonly INeedSomethingOfMyOwn _myobj;
    [ImportingConstructor]
    public MyClass([Import]INeedSomethingOfMyOwn myobj){
        _myobj = myobj;
    }
}
Chris Hayes
  • 3,876
  • 7
  • 42
  • 72