Design Pattern for Static Data Access

I have a scenario in which I have a set of credentials for each environment, for example, for dev env username1 / pwd1, for qa env username2 / pwd2, for setting username3 / pwd3, etc. Now I want to create a class that will return to me the credential set based on env that I submit to it. All data should go within the code (according to my brilliant boss, without xml files and all), which design pattern could I use to make the code elegant and the data can be made extensible in the future?

+4
source share
2 answers

Personally, I use to create a channel attribute:

[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
}

Assembly:

#if DEBUG
// In release mode, this attribute is set by the MSBuild script
[assembly: AssemblyChannel(ChannelType.Dev)]
#else

, MSBuild script ( , ).

, , :

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"];
0

​​.Net, . asp.net, ( config cmd json, )

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration

0

Source: https://habr.com/ru/post/1680101/


All Articles