Skip to content

Instantly share code, notes, and snippets.

@chgeuer
Created February 23, 2012 08:12
Show Gist options
  • Save chgeuer/1891477 to your computer and use it in GitHub Desktop.
Save chgeuer/1891477 to your computer and use it in GitHub Desktop.
MEF - Show how a specific object instance can be injected into a container.
namespace MEFExistingInstanceInjection
{
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
/// <seealso href="http://stackoverflow.com/questions/7684766/is-it-possible-to-inject-an-existing-instance-into-a-mef-plugin"/>
class MEFExistingInstanceInjectionSample
{
static void Main(string[] args)
{
var container = new CompositionContainer(new TypeCatalog(typeof(Foo)));
// Inject THE one and only instance
var instance = new Foo("Hello world");
container.ComposeExportedValue<IFoo>(instance);
var foo = container.GetExportedValue<IFoo>();
Console.WriteLine(foo.Value);
}
}
public interface IFoo { string Value { get; } }
[Export(typeof(IFoo))]
public class Foo : IFoo
{
public Foo(string value) { this.Value = value; }
public string Value { get; private set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment