Multiple instances of the same MEF DLL

Obviously, .NET 4.0 does not have PartCreator / ExportFactory for non-SL. This is what seems to me necessary for this.

I was wondering if anyone could help me (with an example) how to create multiple instances of type EXPORTED in a DLL. They basically say that I have a DLL that contains a ConsoleLogger type and uses the ILogger interface (which I import / export through MEF) ... How do I instantiate a ConsoleLogger whenever I want? Also .. Is it possible?

+7
c # mef
source share
2 answers

One way to do this is to write a factory for the magazine itself and use it as a contract that you export.

public class Logger : ILogger { public Logger(IFoo foo) { } // ... } [Export(typeof(ILoggerFactory))] public class LoggerFactory : ILoggerFactory { [Import] public IFoo Foo { get; set; } public ILogger CreateLogger() { return new Logger(Foo); } } 

Then you simply import the LoggerFactory and call CreateLogger every time you need a logger. This is pretty much the same thing you would do if you imported ExportFactory. The disadvantage is that you need to write a separate factory for each thing you want to create multiple instances.

Another option is to add ExportProvider to your container, which allows you to import factories. In the latest MEF reduction on CodePlex, there is a DynamicInstantiation pattern that shows how to do this.

+8
source share

A preview of MEF 2 adds ExportFactory to .NET 3.5 and 4.0:

  • ExportFactory moved from SL to .net
  • desktop version Some code
  • refactoring and performance enhancements
  • Code Contracts Both builds:
  • strong named signed
0
source share

All Articles