Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MEF Generic Imports

Tags:

c#

generics

mef

I have the following example code using MEF:

public interface IFoo<T> 
{}

public class Foo<T> : IFoo<T> 
{}

[Export(typeof(IFoo<String>))]
public class Foo : Foo<String> 
{}

public class Bar<T>
{
   [Import]
   private readonly IFoo<T> foo;
}

static void Main()
{
   var catalog = new AggregateCatalog();
   catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
   var container = new CompositionContainer(catalog);
   container.ComposeParts();

   var bar = new Bar<String>();
   //bar.foo would be null
}

This doesn't seem to work - the foo field is null. Is this because its type isn't seen by MEF as IFoo<String> ?

like image 723
Lee Atkinson Avatar asked Feb 26 '23 00:02

Lee Atkinson


1 Answers

foo is null because you are creating the instance yourself. You need to have the container create the instance.

Additionally, you will want to check out the GenericCatalog if you plan on working importing/exporting generics.

like image 184
Tom Brothers Avatar answered Feb 27 '23 13:02

Tom Brothers