tags:

views:

230

answers:

2

Apparently .NET 4.0 does not have the PartCreator/ExportFactory for non-SL. Which is something I think I need for this.

I was wondering if someone can help me (with an example please) of how to create multiple instances of the EXPORTED type in a DLL. Basically say I have a DLL that contains a type ConsoleLogger and it uses the interface ILogger (which I import/export through MEF)...How would I create an instance of ConsoleLogger whenever I wanted to? Also..Is this even possible?

+3  A: 

One way to do this is to write a factory for the logger yourself and use that as the contract 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 just import a 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 downside is that you have to write a separate factory for each thing you want to be able to create multiple instances of.

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

Daniel Plaisted
Thanks. I think this will work for my situation.
Travyguy9
A: 

MEF 2 Preview 1 brings ExportFactory into .NET 3.5 and 4.0:

  • ExportFactory moved from SL to .net
  • desktop version Some code
  • refactorings and perf improvements
  • Code Contracts Both assemblies are
  • strong named signed
Ray Hayes