Patrick Desjardins
Patrick Desjardins

Reputation: 140763

C# MEF cannot do type binding?

I would like to bind by type instead to the object instanced.

What I have to do NOW :

var catalog = new AssemblyCatalog(typeof(...).Assembly);

var container = new CompositionContainer(catalog); 
    var batch = new CompositionBatch(); 
var mySamurai = new Samurai(); 
batch.AddPart(mySamurai);//I would prefer the type not an object...    
    container.Compose(batch);
mySamurai.Attack();

That's works BUT I would like to do something like:

var catalog = new AssemblyCatalog(typeof(...).Assembly);
var container = new CompositionContainer(catalog);
var batch = new CompositionBatch();

batch.AddPart(typeof(Samurai));//HERE container.Compose(batch);        
var mySamurai = new Samurai();
mySamurai.Attack(); 

Is that possible with MEF?

Upvotes: 3

Views: 445

Answers (3)

neontapir
neontapir

Reputation: 4736

I don't know much about MEF, but your situation looks like something an IoC Container like Ninject, Unity, StuctureMap, Castle Windsor, et al... would excel at.

Upvotes: 0

Wim Coenen
Wim Coenen

Reputation: 66723

Normally you set up exports and imports in MEF with attributes, instead of configuring them in code like Ninject does.

Even though MEF does not do "configuration in code" out of the box, you can still use the MEFContrib project to do that with the factory export provider.

update: in MEF2-Preview3 attribute-less registration was added.

Also, Mark Seemann blogged about a way to "register" types even without using the new attribute-less registration, by making clever use of property exports and generics.

Upvotes: 1

Daniel Plaisted
Daniel Plaisted

Reputation: 16744

If I'm understanding you correctly, there's no way to do this. MEF can't do anything when it sees fakeEntity2 because MEF never actually "sees" it. You have to pass it to the container as you do with fakeEntity, or you have to export the FakeEntity class, and pull it from the container somehow (ie with GetExportedValue).

Upvotes: 1

Related Questions