【问题标题】:Verify there is no file references between solution projects验证解决方案项目之间没有文件引用
【发布时间】:2018-12-28 11:26:05
【问题描述】:

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

Solution
    - Project1
    - Project2

我希望只有 Project References 从 Project2 到 Project1 像:

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

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

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

如何确定解决方案项目之间没有File References?理想情况下应该是构建错误,但最好的实现方法是什么?

【问题讨论】:

标签: c# .net msbuild solution


【解决方案1】:

我找到了解决方案。可以添加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)。

【讨论】:

    【解决方案2】:

    你可以写一个简单的PowerShell

    $path = "D:\temp\Solution1"
    $extension = "csproj"
    
    
    #-------------------
    
    $projects = Get-ChildItem -Path $path -Recurse -Filter "*.$($extension)"
    
    $projectsList = @()
    
    # Create the project's solution list
    foreach ($project in $projects)
    {
        $projectsList += $project
    }
    
    
    foreach($project in $projectsList)
    {   
        # Read the project xml
        [xml]$proj = [System.IO.File]::ReadAllText($project.FullName)
    
        # loop throught ItemGroup
        foreach($item in $proj.Project.ItemGroup)
        {
    
            # Looking for project reference
            $all = $projectsList | where {$_.Name -eq "$($item.Reference.Include).$($extension)"} 
    
            foreach($ref in $all)
            {
                Write-Warning "Find wrong reference for $($ref.Name) on $($project.Name)"
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 2018-11-03
      • 2011-09-18
      • 1970-01-01
      • 2010-12-11
      相关资源
      最近更新 更多