您知道如何将相同的模块两次添加到具有不同参数的目录中吗?
ITest acc1 = new smalltest("a", 0)
ITest acc2 = new smalltest("b", 1)
AggregateCatalog.Catalogs.Add(??)
AggregateCatalog.Catalogs.Add(??)
提前致谢!
由于 MEF 仅限于属性的使用,并且可以使用 Import 和 Export 属性进行配置,这与 IoC 容器通常提供的灵活性不同,就像Part
在 MEF 中扩展 a 的方式一样,也可以从引用的 DLL 扩展它,您还可以通过创建一个使用[ExportAttribute]
. 属性不仅限于在类上的使用,还可以应用于属性。例如,这样的事情怎么样。
public class PartsToExport
{
[Export(typeof(ITest))]
public Implementation A
{
get { return new Implementation("A", 5); }
}
[Export(typeof(ITest))]
public Implementation B
{
get { return new Implementation("B", 10); }
}
}
public interface ITest
{
void WhoAmI(Action<string, int> action);
}
[Export]
public class Implementation : ITest
{
private string _method;
private readonly int _value;
public Implementation(string method, int value)
{
_method = method;
_value = value;
}
public void WhoAmI(Action<string, int> action)
{
action(_method, _value);
}
}
[TestClass]
public class Tests
{
[TestMethod]
public void Test()
{
var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
CompositionContainer container = new CompositionContainer(catalog);
var tests = container.GetExportedValues<ITest>();
foreach (var test in tests)
{
test.WhoAmI((s, i) => Console.WriteLine("I am {0} with a value of {1}.", s, i));
}
}
}
这会将以下内容输出到控制台:
我是 A,值为 5。
我是 B,值为 10。