c# - 验证解决方案项目之间没有文件引用

标签 c# .net msbuild solution

假设 .NET 解决方案中有两个项目:

Solution
    - Project1
    - Project2

我只想拥有从 Project2 到 Project1 的 Project References,例如:

<ItemGroup>
  <ProjectReference Include="Project1.csproj" />
</ItemGroup>

但有时开发人员会添加错误的 File References 而不是:

<ItemGroup>
  <Reference Include="Project1">
    <HintPath>path\to\Project1.dll</HintPath>
  </Reference>
</ItemGroup>

我如何确定解决方案项目之间没有文件引用?理想情况下,它应该是构建错误,但实现它的最佳方法是什么?

最佳答案

我找到了解决方案。可以添加 MSBuild 任务(目标)来检查所有解决方案项目的文件引用。此任务必须添加到所有项目或 Directory.Build.targets。这是目标:

<Project>
  <Target Name="BeforeBuild">
    <Message Text="Analyzing '$(MSBuildProjectFile)' for file references between solution projects...&#xA;" />

    <GetSolutionProjects Solution="$(MSBuildThisFileDirectory)\YourSolutionName.sln">
      <Output ItemName="Projects" TaskParameter="Output"/>
    </GetSolutionProjects>

    <PropertyGroup>
      <Expression>(@(Projects->'%(ProjectName)', '|')).dll</Expression>
    </PropertyGroup>

    <XmlRead XmlFileName="$(MSBuildProjectFile)" XPath="//Project/ItemGroup/Reference/HintPath">
      <Output ItemName="FileReferences" TaskParameter="Value"/>
    </XmlRead>

    <RegexMatch Input="@(FileReferences)" Expression="$(Expression)">
      <Output TaskParameter="Output" ItemName ="ProjectReferences" />
    </RegexMatch>

    <Error Text="There must be no file references between solution projects, but it was found in '$(MSBuildProjectFile)' to the following file(s): %(ProjectReferences.Identity)"
           Condition="'%(ProjectReferences.Identity)' != ''" />
  </Target>
</Project>

此目标使用 MSBuild Community Tasks因此不要忘记将此 NuGet 包添加到您的所有项目中(或添加到 Directory.Build.props)。

关于c# - 验证解决方案项目之间没有文件引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53957818/

相关文章:

c# - 将通过 HTTP 上传到 ASP.NET 的文件进一步上传到 C# 和 SSH.NET 中的 SFTP 服务器

visual-studio-2010 - 如何使用命令行取消 Visual Studio 构建?

msbuild - 尝试使用 Sublime Text 到 msbuild 时出现错误 6

build - TFS 2013 版本是否支持 VS 2012 解决方案?

c# - 读取字符串中的特定行?

c# - 根据值确定常量的名称

c# - 浏览注册表文件

c# - 服务已停止,但进程仍保持一分钟

c# - 捕获异步方法中的异常

c# - Swagger-Codegen 自定义设置