C# как получить значение свойства из класса, используя дженерики - PullRequest
0 голосов
/ 15 января 2020

Я работаю над asp. net core webapi и использую настройки приложений. json для сохранения некоторых настроек. У меня есть класс, чтобы получить значение свойства из appsettings, используя IOptions <>.

Интересно, есть ли простой способ использовать generi c для получения значения свойства вместо создания имен отдельных методов, как я делаю ниже:

public class NotificationOptionsProvider
{
    private readonly IOptions<NotificationOptions> _notificationSettings;
    public NotificationOptionsProvider(IOptions<NotificationOptions> notificationSettings)
    {
        _notificationSettings = notificationSettings;
        InviteNotificationContent = new InviteNotificationContent();
    }

    public string GetRecipientUserRole()
    {
        if (string.IsNullOrWhiteSpace(_notificationSettings.Value.RecipientUserRole))
        {
            throw new Exception("RecipientUserRole is not configured");
        }

        return _notificationSettings.Value.RecipientUserRole;
    }

    public string GetInvitationReminderTemplateCode()
    {
        if (string.IsNullOrWhiteSpace(_notificationSettings.Value.AssignReminderTemplateCode))
        {
            throw new Exception("InvitationReminderTemplateCode is not configured");
        }

        return _notificationSettings.Value.AssignReminderTemplateCode;
    }

    public string GetSessionBookedTemplateCode()
    {
        if (string.IsNullOrWhiteSpace(_notificationSettings.Value.SessionBookedTemplateCode))
        {
            throw new Exception("SessionBookedTemplateCode is not configured");
        }

        return _notificationSettings.Value.SessionBookedTemplateCode;
    }       
}

Спасибо

Ответы [ 2 ]

3 голосов
/ 15 января 2020

Вы можете написать что-то вроде:

public string GetSetting(Func<NotificationOptions, string> selector)
{
    string value = selector(_notificationSettings.Value);
    if (string.IsNullOrWhiteSpace(value))
    {
        throw new Exception("Not configured");
    }
    return value;
}

И назвать это как:

GetSetting(x => x.AssignReminderTemplateCode);
1 голос
/ 15 января 2020

Просто уточняю отличный ответ кантона7; Вы можете сохранить текст исключения, например, так:

public string GetSetting(Expression<Func<NotificationOptions, string>> selector)
{
    Func<NotificationOptions, string> func = selector.Compile();
    string value = selector(_notificationSettings.Value);
    if (string.IsNullOrWhiteSpace(value))
    {
        var expression = (MemberExpression)selector.Body;
        throw new Exception($"{expression.Member.Name} is not configured");
    }
    return value;
}

Хотя учтите, что вызов .Compile() приведет к снижению производительности.

...