是否可以为我的组件添加一些额外的属性,然后使用一些自定义逻辑/可能从数据存储中设置/补充?与在cab / unity中添加一些自定义构建器策略类似吗?
UPDATE e.g。
assuming a class has these properties
[MyImport] string name1 { get; set }
[MyImport] MyType name2 { get; set }
[MyGuid] Guid { get; set; }
使用自定义属性MyImport和MyGuid,它们通过MEF的“扩展”解析(在[导入]解析后执行)并且具有沿这些行的代码
// property SET
var valu = myDBStore.GetValue( instanceGUID, propertyInfo.Name);
propertyInfo.SetValue( instance, TypeDescripter.GetConverter(valu).ConvertTo(propertyType), null);
// property GET - for example only, used during dehydration outside of MEF !
var valu = propertyInfo.GetValue( instance, null);
myDBStore.SetValue( instanceGUID, propertyInfo.Name, TypeDescripter.GetConverter(valu).ConvertTo(typeof(string));
// the above is pseudo code only, pls no comments on correct args/syntax :)
答案 0 :(得分:2)
修改强>
components which are then set/hydrated using some custom logic/perhaps from a data store
可以通过“ExportFactory”来做到这一点。
// "ExportFactory"
public sealed class DataStoreProvider
{
[Export(typeof(Model))]
public Model Item
{
get
{
return [custom logic];
}
}
}
public class NeedsModel
{
[Import(typeof(Model))]
public Model Item { get; set; }
}
初步答复
这可以通过MEF Lazy<T, TMetadata>
来实现。
public interface ISomeMetadata
{
string UsefulInfo { get; }
}
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple=false)]
public class ExportBaseAttribute : ExportAttribute, ISomeMetadata
{
public ExportBaseAttribute(string usefulInfo)
:base(typeof(BaseExport))
{
UsefulInfo = usefulInfo;
}
public string UsefulInfo { get; private set; }
}
// BaseExport class is not needed.. just showing advanced attribute usage.
public abstract class BaseExport { }
[ExportBase("Useful Filter Information")]
public class SomeExport : BaseExport
{
}
然后,在您的主持人(作曲家)中,您可以
[ImportMany(typeof(BaseExport))]
Lazy<BaseExport, ISomeMetadata>[] _baseExports
撰写后,您可以使用.Metadata
var goodExports = from export in _baseExports
where export.Metadata.UsefulInfo ...
select export;