Is it possible to insert an existing instance into the MEF plugin?

We are creating an application that supports plugins using MEF. We determine what types of plugins a user can create and want to use dependency injection to provide this type of plugin with the data it needs.

For example, we create a plugin that can display a list. To achieve this, he needs an existing instance of IRepository for the type of data that the list will display.

An IRepository is created somewhere else in the datacontext class, so we cannot allow MEF to instantiate an IRepository.

My idea is to insert an existing instance of IRepository into the plugin through importingconstructor, however, for this I need to make an already created IRepository, known to MEF, and I was not able to figure out how to do this. Any help would be appreciated.

+4
source share
1 answer

The easiest way is to compose an existing value in the container, for example:

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

But this will only allow 1 instance of IRepository exist, since it does not give you direct control over the generated ComposablePart . If you want finer-grained control, you can use CompositionBatch for a 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:

 var batch2 = new CompositionBatch(null, new[] { repoPart }); var repo2 = // Get new repo var repo2Part = batch2.AddExportedValue<IRepository>(repo2); container.Compose(batch2); 

Since I have access to the ComposablePart instance provided by the package, I can delete it later. There are other ways to import parts without attributes, usually through exporting properties:

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

But this, of course, will require you to create an instance of your repository during linking, which may or may not be possible.

Finally, it is possible to use an alternative programming model. By default (and the most common) in MEF, an attribute programming model is used, in which you use the [Export] and [Import] attributes to control your composition, but in MEFContrib (and the upcoming one in MEF2) you can use the registration programming model, the details are compiled on based on a mechanism similar to most other IoC containers.

+8
source

All Articles