Is it possible to inject an existing instance into a MEF plugin?

女生的网名这么多〃 提交于 2019-12-04 10:59:23

The easiest way is to compose an existing value in the container, e.g.:

var repo = // Create repo
container.ComposeExportedValue<IRepository>(repo);

But this will only allow 1 instance of the IRepository to exist, because it doesn't give you direct control over the ComposablePart that is created. If you want more fine grained control, you can use a CompositionBatch to great effect:

var batch = new CompositionBatch();
var repo = // Create repo

var repoPart = batch.AddExportedValue<IRepository>(repo);
container.Compose(batch);

// repo will now be injected on any matching [Import] or [ImportingConstructor]

And later on:

var batch2 = new CompositionBatch(null, new[] { repoPart });
var repo2 = // Get new repo

var repo2Part = batch2.AddExportedValue<IRepository>(repo2);
container.Compose(batch2);

Because I have access to the ComposablePart instance provided by the batch, I can remove it later on. There are other ways of importing attribute-less parts, generally through property exports:

[Export(typeof(IRepository))]
public IRepository Repository
{
    get { return CreateRepository(); }
}

But that of course would require you to be able to create an instance of your repository at composition time, which may or may not be possible.

Lastly, there is the option to use an alternative programming model. The default (and most common) in MEF is the attributed programming model, whereby you utilise [Export] and [Import] attributes to control your composition, but in MEFContrib (and forthcoming in MEF2) is the ability to use a registration programming model whereby parts are composed based on a mechanism similar to most other IoC containers.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!