Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

c# - Multiple Instances of a single MEF DLL

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...