davidwhitney / System.Configuration.Abstractions

Injectable, mockable, extensible, configuration for .NET
MIT License
42 stars 7 forks source link

Guid Parsing #14

Closed kfrancis closed 6 years ago

kfrancis commented 6 years ago

The following doesn't work:

ConfigurationManager.Instance.AppSettings.AppSetting<Guid>("someGuidVal", () => null)

Just can't parse it. What's the option here? I can't tell from your documentation ..

oliversweb commented 6 years ago

Firstly; I don't think there is an 'out of the box' converter for string to Guid so whatever string you read out of the config will not converter automatically to a Guid, you will need a custom converter of type IConvertType.

Secondly; a Guid is a Value Type (Struct) so providing a null as a default will not work, , you will still need a custom converter of type IConvertType.

Try adding this converter;

    public class CustomGuidConverter : IConvertType
    {
        public Type TargetType { get { return typeof(Guid); } }

        public object Convert(string configurationValue)
        {
            return Guid.Parse(configurationValue);
        }
    }

Initialise it something like this;

new AppSettingsExtended(_underlyingConfiguration, null, new[] { new CustomGuidConverter() });

Then use it something like this;

_wrapper.AppSetting<Guid>("someGuidVal", whenConversionFailsInsteadOfThrowingDefaultException: () => Guid.Empty)

Or like this if you just want to capture missing key exceptions;

_wrapper.AppSetting<Guid>("someMissingGuidVal", whenKeyNotFoundInsteadOfThrowingDefaultException: () => Guid.Empty);

Or if you need a null returned then use a nullable Guid as the generic type;

_wrapper.AppSetting<Guid?>("someMissingGuidVal", whenKeyNotFoundInsteadOfThrowingDefaultException: () => null);

Hope that helps.

davidwhitney commented 6 years ago

Version 2.0.2.44 ports @oliversweb work in as default behaviour - this should now work OOTB <3