我使用無屬性的方法來配置MEF。
我閱讀下面的文章:
http://msdn.microsoft.com/en-us/magazine/jj133818.aspx
http://blogs.microsoft.co.il/blogs/bnaya/archive/2013/01/12/mef-2-0-mini-series-part-4-fluent-import.aspxMEF 2:導入很多
測試代碼(控制檯應用程序項目,.NET 4.5):
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Registration;
using System.Linq;
namespace MEF2
{
public interface IPlugin
{
void Run();
}
public interface IPluginMetadata
{
string Name { get; }
string Version { get; }
}
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple=false)]
public class PluginMetadataAttribute : ExportAttribute, IPluginMetadata
{
public string Name { get; set; }
public string Version { get; set; }
public PluginMetadataAttribute(string name, string version)
: base(typeof(IPlugin))
{
Name = name;
Version = version;
}
}
[PluginMetadata("Plugin1", "1.0.0.0")]
public class Plugin1 : IPlugin
{
public void Run()
{
Console.WriteLine("Plugin1 runed");
}
}
[PluginMetadata("Plugin2", "2.0.0.0")]
public class Plugin2 : IPlugin
{
public void Run()
{
Console.WriteLine("Plugin2 runed");
}
}
class Program
{
CompositionContainer container;
IEnumerable<Lazy<IPlugin, IPluginMetadata>> plugins = Enumerable.Empty<Lazy<IPlugin, IPluginMetadata>>();
static void Main(string[] args)
{
var program = new Program();
foreach (var plugn in program.plugins) {
Console.WriteLine("{0}, {1}", plugn.Metadata.Name, plugn.Metadata.Version);
plugn.Value.Run();
}
}
Program()
{
var builder = new RegistrationBuilder();
builder
.ForTypesDerivedFrom<IPlugin>()
.Export<IPlugin>();
builder
.ForType<Program>()
.Export()
.ImportProperties<IPlugin>(
propertyFilter => true,
(propertyInfo, importBuilder) => {
importBuilder.AsMany();
}
);
var catalog = new AggregateCatalog(
new AssemblyCatalog(typeof(Program).Assembly, builder)
);
container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
}
出口工作正常。
但是,當我嘗試導入很多它不起作用。
請幫我解決這個問題。