0

我有一个文本模板片段,它生成一个Solution具有Assemblies属性的类,以列出 Visual Studio 解决方案中的所有项目程序集,以帮助配置 IoC 容器(GitHubNuGet)。但是,当项目放在解决方案文件夹中时,它会失败。如何使该脚本的解决方案文件夹透明?有问题的代码是:

<#+

    class SolutionAssemblyNames : IEnumerable<string>
    {
        public SolutionAssemblyNames(ITextTemplatingEngineHost host)
        {
            Host = host;
        }

        public IEnumerator<string> GetEnumerator() => Assemblies.GetEnumerator();
        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
        IEnumerable<string> Assemblies => Projects
            .Select(p => p?.Properties?.Item("AssemblyName")?.Value as string)
            .Distinct().Where(a => !string.IsNullOrWhiteSpace(a));

        IEnumerable<Project> Projects => VisualStudio.Solution.Projects.OfType<Project>();
        DTE VisualStudio => (Host as IServiceProvider).GetService(typeof(DTE)) as DTE;
        ITextTemplatingEngineHost Host { get; }
    }
#>
4

1 回答 1

1

DTE 不返回项目的平面列表,因此您需要主动检查解决方案文件夹,然后递归读取其子项目(因为您可以在解决方案文件夹中包含解决方案文件夹等)

    IEnumerable<string> Assemblies => Projects
        .SelectMany(GetProjectAndSubProjects) // ################# Flatten the list of projects
        .Select(p => p?.Properties?.Item("AssemblyName")?.Value as string)
        .Distinct()
        .Where(a => !string.IsNullOrWhiteSpace(a));

    IEnumerable<Project> Projects => VisualStudio.Solution.Projects.OfType<Project>();

    private static IEnumerable<EnvDTE.Project> GetProjectAndSubProjects(EnvDTE.Project project)
    {
        if (project.Kind == VsProjectKindSolutionFolder)
        {
            return project.ProjectItems
                .OfType<EnvDTE.ProjectItem>()
                .Select(p => p.SubProject)
                .Where(p => p != null)
                .SelectMany(GetProjectAndSubProjects);
        }

        return new[] { project };
    }

    // Copied from EnvDTE80.ProjectKinds.vsProjectKindSolutionFolder
    private const string VsProjectKindSolutionFolder = "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}";
于 2018-09-25T00:24:20.090 回答