General import of MEF

I have the following code example 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 does not work - the field is foo null . Is it because its type is not considered by MEF as IFoo<String> ?

+4
source share
1 answer

foo is null since you are instantiating yourself. You need to create a container for the instance.

In addition, you will want to check out GenericCatalog if you plan to work with import / export of generics.

+8
source

Source: https://habr.com/ru/post/1340961/


All Articles