我个人是习惯创建频道属性的:
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyChannelAttribute : Attribute
{
public ChannelType Type { get; private set; }
public AssemblyChannelAttribute(ChannelType type)
{
this.Type = type;
}
}
public enum ChannelType
{
Dev,
Beta,
PreProd,
Prod
}
这个属性是在程序集上设置的:
#if DEBUG
// In release mode, this attribute is set by the MSBuild script
[assembly: AssemblyChannel(ChannelType.Dev)]
#else
正如评论所说,该属性的值是由我的 MSBuild 脚本在编译时设置的(与我的项目太相关,无法向您展示这部分)。
完成所有这些设置后,您可以像这样创建一个简单的单例:
public class Credentials
{
private static readonly Lazy<Credentials> instanceHolder =
new Lazy<Credentials>(() => new Credentials());
public IReadOnlyDictionary<string, string> Passwords { get; private set; }
public Credentials Instance { get { return instanceHolder.Value; } }
private Credentials()
{
var channel = typeof(Credentials).Assembly
.GetCustomAttributes<AssemblyChannelAttribute>()
.ElementAt(0)
.Type;
switch (channel)
{
case ChannelType.Dev:
this.Passwords = new ReadOnlyDictionary<string, string>(new Dictionary<string, string>
{
["User1"] = "Pwd1",
["User2"] = "Pwd2",
// etc
});
break;
case ChannelType.Beta:
// etc
break;
case ChannelType.PreProd:
// etc
break;
case ChannelType.Prod:
// etc
break;
}
}
}
然后您可以像这样访问您的凭据:
var password = Credentials.Instance.Passwords["User1"];