在TT自动化脚本中跳过解决方案文件夹

时间:2018-09-24 22:19:43

标签: c# visual-studio envdte texttemplate

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

<#+

    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; }
    }
#>

1 个答案:

答案 0 :(得分: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}";