正如 Wim 所说,这并不是开箱即用的原生支持。如果您希望能够执行以下操作:
[ImportMany]
public IEnumerable<Service> _services { get; set; }
...不使用工厂(如ServiceProvider
Wim 详述的),则出口提供者将起作用,例如:
public class ServiceExportProvider : ExportProvider
{
private const string ContractName = AttributedModelServices.GetContractName(typeof(Service));
public ExportProvider SourceProvider { get; set; }
protected override IEnumerable<Export> GetExportsCore(ImportDefinition def, AtomicComposition ac)
{
if (SourceProvider == null)
throw new InvalidOperationException("SourceProvider property must be set.");
if (def.ContractName.Equals(ContractName))
{
return SourceProvider
.GetExports<IDependency>()
.Select(e => new Export(def.ContractName, () => new Service(e.Value)));
}
return Enumerable.Empty<Export>();
}
}
您不需要[Export]
您的Service
类型(实际上这可能会导致问题),但如果您已使用容器向提供者注册并设置[Import]
属性,则可以[ImportMany]
使用实例:Service
SourceProvider
var catalog = // create catalogs/
var provider = new ServiceExportProvider();
var container = new CompositionContainer(catalog, provider);
provider.SourceProvider = container;