The problem appears to be that you expect to import a single ExportFactory<IFoo>
, but you have exported two different IFoo
implementations. In your example, MEF wouldn't be able to decide between both implementations.
You probably want to import multiple factories including metadata like this:
[ImportMany]
private IEnumerable<ExportFactory<IFoo,IFooMeta>> FooFactories
{
get;
set;
}
where IFooMeta
would be declared like this:
public interface IFooMeta
{
string CompType { get; }
}
and then you could implement CreateComponent
like this:
public IFoo CreateComponent(string name, string compType)
{
var matchingFactory = FooFactories.FirstOrDefault(
x => x.Metadata.CompType == compType);
if (matchingFactory == null)
{
throw new ArgumentException(
string.Format("'{0}' is not a known compType", compType),
"compType");
}
else
{
IFoo foo = matchingFactory.CreateExport().Value;
foo.Name = name;
return foo;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…