目前,我正在使用MEF开发Visual Studio 2010的扩展,我需要初始化我的全局状态。我正在尝试在Package.Initialize方法
中执行此操作[PackageRegistration(UseManagedResourcesOnly = true)]
[InstalledProductRegistration("#110", "#112", "1.0.0.0", IconResourceID = 400)]
[Guid("1AF4B41B-F2DF-4F49-965A-816A103ADFEF")]
public sealed class MyPackage : Package
{
protected override void Initialize()
{
ContainerConfigurator.Configure();
ContainerConfigurator.IsInitialized = true;
base.Initialize();
}
}
此外,我还有一个使用此状态的MEF分类器提供程序
[Export(typeof(IClassifierProvider))]
[Name("This is my provider")]
[ContentType("DebugOutput")]
[ContentType("Output")]
public class MyClassifierProvider : IClassifierProvider
{
[Import]
private IClassificationTypeRegistryService _classificationRegistry = null; // MEF
public IClassifier GetClassifier(ITextBuffer textBuffer)
{
// This always false
if (!ContainerConfigurator.IsInitialized)
throw new InvalidOperationException();
return textBuffer.Properties.GetOrCreateSingletonProperty(() => new TypedClassifier(ServiceLocator.Current, _classificationRegistry));
}
}
package和MEF分类器都在同一个程序集中。当我开始调试并放置一个断点时,我看到这个组件被加载了。但MyClassifierProvider已在MyPackage.Initialize调用之前初始化。因此,在启动任何MEF组件之前,我无法初始化我的全局状态。任何人都可以解释为什么以及如何避免这种行为?
由于
答案 0 :(得分:20)
我找到了答案。有必要添加ProvideAutoLoad属性
http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.vsconstants(v=vs.80).aspx
http://dotneteers.net/blogs/divedeeper/archive/2008/03/23/LVNSideBar1.aspx
所以最后的类声明是
[PackageRegistration(UseManagedResourcesOnly = true)]
[InstalledProductRegistration("#110", "#112", "1.0.0.0", IconResourceID = 400)]
[Guid("1AF4B41B-F2DF-4F49-965A-816A103ADFEF")]
[ProvideAutoLoad("ADFC4E64-0397-11D1-9F4E-00A0C911004F")]
public sealed class MyPackage : Package