Roslyn 分析器中的依赖注入

问题描述 投票:0回答:2

我有一个自定义的 Roslyn 分析器,它继承自

DiagnosticAnalyzer
。它打包在 VSIX 扩展中,其中包含自定义
Package
类。我想将具有设置的类实例(
CodeAnalysisSettings
实例)从包传递到我的
DiagnosticAnalyzer

我尝试使用 MEF 来实现此目的。我已使用以下代码在 VS Package 中注册了我的设置类的实例:

protected override void Initialize()
{
    base.Initialize();
    IComponentModel componentModel = Package.GetGlobalService(typeof(SComponentModel)) as IComponentModel;
    new CompositionContainer(componentModel.DefaultCatalog).ComposeExportedValue(
                new CodeAnalysisSettings(...));
}

分析仪如下所示:

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class MyAnalyzer : DiagnosticAnalyzer
{
    [Import]
    public CodeAnalysisSettings Settings { get; set; }
}

设置类:

[Export]
public class CodeAnalysisSettings
{
    public CodeAnalysisSettings()
    {
    }

    public bool RecursiveAnalysisEnabled { get; }
}

由于某种原因,

Settings
属性未导入 - 它的值始终为空。

请帮忙。

c# dependency-injection mef roslyn vsix
2个回答
1
投票

我最终使用了一个服务定位器(CommonServiceLocator 包),它使用 MEF 容器作为源。

由于 VS 基础设施不允许添加新的注册(

IComponentModel.DefaultCatalog
抛出一个异常,表明不再支持此功能),所以我在
Package.Initialize()
中创建了一个新容器:

var container = new CompositionContainer(CompositionOptions.Default, componentModel.DefaultExportProvider);
container.ComposeExportedValue<CodeAnalysisSettings>(new CodeAnalysisSettings(...));
var serviceLocator = new MefServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => serviceLocator);

Roslyn 诊断消耗此依赖项:

var settings = CodeAnalysisSettings.Default;
if (ServiceLocator.IsLocationProviderSet)
    settings = ServiceLocator.GetInstance<CodeAnalysisSettings>();

0
投票

Microsoft VSIX 社区工具包有一个依赖注入 Nuget 包,可将 DI 添加到 VSIX 扩展中。它允许您添加自己的 IOC 容器或使用他们的。

GitHub 上的 VSIX 社区工具包包

© www.soinside.com 2019 - 2024. All rights reserved.