开发者

C# MEF cannot do type binding?

开发者 https://www.devze.com 2023-02-13 01:12 出处:网络
I would like to bind by type instead to the object instanced. What I have to do NOW : var catalog = new AssemblyCatalog(typeof(...).Assembly);

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.Comp开发者_JAVA技巧ose(batch);        
var mySamurai = new Samurai();
mySamurai.Attack(); 

Is that possible with MEF?


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.


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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消