我有一个类似的问题。
我正在开发一个带有 ASP.Net 后端的 Xamarin 移动应用程序。我有一个包含后端服务器 URL 的设置类:
namespace Company.Mobile
{
public static class Settings
{
#if DEBUG
const string WebApplicationBaseUrl = "https://local-pc:44335/";
#else
const string WebApplicationBaseUrl = "https://company.com/";
#endif
}
}
它对调试和发布配置有不同的值。但是当几个开发人员开始从事该项目时,这并没有奏效。每台开发机器都有自己的 IP 地址,手机需要使用唯一的 IP 地址进行连接。
我需要在每台开发机器上从文件或环境变量中设置常量值。这就是Fody适合的地方。我用它来创建一个in solution weaver。以下是详细信息。
我将我的Settings
课程放在 Xamarin 应用程序项目中。该项目必须包含 Fody Nuget 包:
<ItemGroup>
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Fody" Version="6.2.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup Condition="'$(Configuration)' == 'Debug'">
<WeaverFiles Include="$(SolutionDir)Company.Mobile.Models\bin\Debug\netstandard2.0\Company.Mobile.Models.dll" WeaverClassNames="SetDevServerUrlWeaver" />
</ItemGroup>
我只在调试配置上进行设置,因为我不希望在发布版本上发生替换。
weaver 类放置在移动项目所依赖的类库项目 (Company.Mobile.Models) 中(您不需要也不应该有这种依赖关系,但 Fody 文档明确表示包含 weaver 的项目必须是在发出编织程序集的项目之前构建)。这个库项目包括 FodyHelpers Nuget 包:
<ItemGroup Condition="'$(Configuration)' == 'Debug'">
<PackageReference Include="FodyHelpers" Version="6.2.0" />
</ItemGroup>
weaver 类定义如下:
#if DEBUG
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Fody;
namespace Company.Mobile.Models
{
public class SetDevServerUrlWeaver : BaseModuleWeaver
{
private const string SettingsClassName = "Settings",
DevServerUrlFieldName = "WebApplicationBaseUrl",
DevServerUrlSettingFileName = "devServerUrl.txt";
public override void Execute()
{
var target = this.ModuleDefinition.Types.SingleOrDefault(t => t.IsClass && t.Name == SettingsClassName);
var targetField = target.Fields.Single(f => f.Name == DevServerUrlFieldName);
try
{
targetField.Constant = File.ReadAllText(Path.Combine(this.ProjectDirectoryPath, DevServerUrlSettingFileName));
}
catch
{
this.WriteError($"Place a file named {DevServerUrlSettingFileName} and place in it the dev server URL");
throw;
}
}
public override IEnumerable<string> GetAssembliesForScanning()
{
yield return "Company.Mobile";
}
}
}
#endif
这是放置在移动应用程序项目中的 FodyWeavers.xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<SetDevServerUrlWeaver />
</Weavers>
devServerUrl.txt 只包含我的本地 IP
https://192.168.1.111:44335/
:。不得将此文件添加到源代码管理中。将它添加到您的源代码管理忽略文件中,以便每个开发人员都有自己的版本。
您可以轻松地从环境变量 ( System.Environment.GetEnvironmentVariable
) 或任何地方而不是文件中读取替换值。
我希望有更好的方法来做到这一点,比如 Roslyn,或者这个属性似乎可以完成这项工作,但事实并非如此。