我可以在类的静态构造函数中保存它吗?
public class Connect:IDTExtensibility2, IDTCommandTarget
static Connect()
{
//hydrate static properties?
}
[Import]
public static Action<ProjectLogicChecks> Display { get; set; }
[Export(typeof(Action<ProjectLogicChecks>))]
private static void DisplayResults( CheckProcesses _checkResults)
{
MessageBox.Show(_checkResults.ProjectLogicCheck.AssemblyName + " has problems=" +
_checkResults.ProjectLogicCheck.HasProblems);
}
答案 0 :(得分:15)
不,MEF不支持静态导入。
答案 1 :(得分:2)
您可以使用[ImportingConstructor]并在构造函数中设置静态属性。
private static RandomService Random { get; set; }
[ImportingConstructor]
public ClientViewModel(RandomService random)
{
Random = random;
}
只是不要将它设置为静态字段。
答案 2 :(得分:1)
这比我想象的要容易。
static Connect()
{
var batch = new CompositionBatch( );
CompositionContainer container;
var reflectionCatalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly( ));
var extensionPath = System.IO.Path.Combine(Environment.CurrentDirectory, "extensions");
if (System.IO.Directory.Exists(extensionPath))
{
var directoryCatalog = new DirectoryCatalog(extensionPath);
var defaultCatalogEp = new CatalogExportProvider(reflectionCatalog);
container=new CompositionContainer(directoryCatalog, defaultCatalogEp);
defaultCatalogEp.SourceProvider=container;
}
else
container = new CompositionContainer(reflectionCatalog);
container.Compose(batch);
//Setting a static property
Display=container.GetExportedValue<Action<IEnumerable< ProjectLogicChecks>>>( );
}
将类型更改为Action<IEnumerable<ProjectLogicChecks>>
,以便我可以显示多个项目或整个解决方案的结果,而不仅仅是一个。