在Funq和可能大多数其他 IoC 容器中,我可以简单地执行此操作来配置类型:
container.Register<ISomeThing>(c => new SomeThing());
我如何在不使用属性的情况下快速扩展 MEF(或使用现有的 MEF 功能)来做同样的事情。
以下是我认为我可以做到的方式:
var container = new CompositionContainer();
var batch = new CompositionBatch();
batch.AddExport<ISomeThing>(() => new SomeThing());
batch.AddExportedValue(batch);
container.Compose(batch);
使用此扩展方法CompositionBatch
:
public static ComposablePart AddExport<TKey>(this CompositionBatch batch, Func<object> func)
{
var typeString = typeof(TKey).ToString();
return batch.AddExport(
new Export(
new ExportDefinition(
typeString,
new Dictionary<string, object>() { { "ExportTypeIdentity", typeString } }),
func));
}
如果我以后这样做:
var a = container.GetExport<ISomeThing>().Value;
var b = container.GetExport<ISomeThing>().Value;
两个实例都是一样的。如何强制(配置)它们为不同的实例?
如果这不是要走的路,我将如何在 MEF 中做到这一点?