2011-08-30 132 views
9

目前,我正在使用MEF開發Visual Studio 2010的擴展,並且需要初始化我的全局狀態。我試圖做到這一點在Package.Initialize方法Visual Studio包調試時不調用Visual Studio包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(); 
    } 
} 

而且我有一個使用這種狀態

[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)); 
    } 
} 

的兩個包和MEF分類是在同一組件上的MEF分類供應商。當我開始調試並放置一個斷點時,我看到這個組裝被加載。但MyClassifierProvider已在MyPackage.Initialize調用之前初始化。所以我無法在啓動任何MEF組件之前初始化我的全局狀態。任何人都可以解釋爲什麼以及如何避免這種行爲?

謝謝

回答

19

我找到了答案。這是需要添加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 
+1

第一個鏈接是錯誤的,它鏈接到VSConstants,該ProvideAutoLoad幫助在這裏找到:http://msdn.microsoft.com/en-us/library/Microsoft.VisualStudio.Shell.ProvideAutoLoadAttribute.aspx –

+0

'ProvideAutoLoad'屬性仍然有效(至少對於VS 2015) – CrazyIvan1974