单MEF DLL的多个实例 [英] Multiple Instances of a single MEF DLL
问题描述
显然.NET 4.0不具有非SL的PartCreator / ExportFactory。这是我想我需要这个。
Apparently .NET 4.0 does not have the PartCreator/ExportFactory for non-SL. Which is something I think I need for this.
我在想,如果有人能帮助我(用一个例子请)如何创建在导出类型的多个实例一个DLL。基本上说,我有一个包含类型ConsoleLogger一个DLL,它使用的接口ILogger(我通过导入MEF /导出)...我怎么会创造ConsoleLogger的一个实例,每当我想? Also..Is这甚至可能吗?
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?
推荐答案
要做到这一点的方法之一是写的记录自己和利用工厂。因为你出口合同
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);
}
}
然后你只需导入的LoggerFactory,并调用CreateLogger每时间你需要一个记录器。这是相当多,如果你输入ExportFactory你会做同样的事情。缺点是,你必须为你写希望能够创造的多个实例每一件事情一个单独的工厂。
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.
另一种选择是一个ExportProvider添加到您的容器这允许您导入工厂。在 CodePlex上最新MEF下降,有一个样品DynamicInstantiation它展示了如何做到这一点。
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.
这篇关于单MEF DLL的多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!