The easiest way is to compose an existing value in the container, for example:
var 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 =
And later:
var batch2 = new CompositionBatch(null, new[] { repoPart }); var repo2 =
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.
source share