独自のカタログを作成する必要があります。これは簡単な作業ではありませんが、ここに例を示します
(私はそれを自分で使用していません。ヘリテッドエクスポートで同様の問題を解決できます)
リンクが切れた場合は、ここでコードを繰り返します。
public class ConventionalCatalog : ComposablePartCatalog {
private List<ComposablePartDefinition> _parts = new List<ComposablePartDefinition>();
public void RegisterType<TImplementation, TContract>() {
var part = ReflectionModelServices.CreatePartDefinition(new Lazy<Type>(() => typeof(TImplementation)),
false,
new Lazy<IEnumerable<ImportDefinition>>(() => GetImportDefinitions(typeof(TImplementation))),
new Lazy<IEnumerable<ExportDefinition>>(() => GetExportDefinitions(typeof(TImplementation), typeof(TContract))),
new Lazy<IDictionary<string, object>>(() => new Dictionary<string, object>()),
null);
_parts.Add(part);
}
private ImportDefinition[] GetImportDefinitions(Type implementationType) {
var constructors = implementationType.GetConstructors()[0];
var imports = new List<ImportDefinition>();
foreach (var param in constructors.GetParameters()) {
imports.Add(ReflectionModelServices.CreateImportDefinition(
new Lazy<ParameterInfo>(() => param),
AttributedModelServices.GetContractName(param.ParameterType),
AttributedModelServices.GetTypeIdentity(param.ParameterType),
Enumerable.Empty<KeyValuePair<string,Type>>(),
ImportCardinality.ExactlyOne,
CreationPolicy.Any,
null));
}
return imports.ToArray();
}
private ExportDefinition[] GetExportDefinitions(Type implementationType, Type contractType) {
var lazyMember = new LazyMemberInfo(implementationType);
var contracName = AttributedModelServices.GetContractName(contractType);
var metadata = new Lazy<IDictionary<string, object>>(() => {
var md = new Dictionary<string, object>();
md.Add(CompositionConstants.ExportTypeIdentityMetadataName,
AttributedModelServices.GetTypeIdentity(contractType));
return md;
});
return new ExportDefinition[] {
ReflectionModelServices.CreateExportDefinition(lazyMember, contracName, metadata, null)
};
}
public override IQueryable<ComposablePartDefinition> Parts {
get { return _parts.AsQueryable(); }
}
}
次のように使用します。
using (var myCatalog = new ConventionalCatalog()) {
myCatalog.RegisterType<MyClass, IMyClass>();
using (var container = new CompositionContainer(myCatalog)) {
container.ComposeParts(this);
...
}
}