D
D
D8i2020-08-08 14:47:38
ASP.NET
D8i, 2020-08-08 14:47:38

Can the .Configure() method configure other types than the standard ones?

There is a class with methods: Emote.Parse(string) - returns Emote, Emote.TryParse(string) - returns bool, etc.

There is a parameter class:

public class EmotesOptions
{
    public Emote CheckMark { get; set; }
    public Emote Clock { get; set; }
}


Is it possible to somehow configure the above type with the Options pattern?
This implementation obviously didn't work for me:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<EmotesOptions>(Configuration.GetSection("Emotes");
}


Maybe you can change something in this method so that the configuration takes a string from a file and converts it to a new type?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D8i, 2020-10-13
@D8i

I found the answer to the question: Let's
use Type Converter.
Let's create a class EmotesConverter dependent on TypeConverter with the following content:

public class EmotesConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(string) ||
               base.CanConvertFrom(context, sourceType);
    }
        
    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        return value is string emoteString
            ? Emote.Parse(emoteString)
            : base.ConvertFrom(context, culture, value);
    }
}

Let's add an attribute to the options class:
[TypeConverter(typeof(EmotesConverter))]
public class EmotesOptions
{
    public Emote CheckMark { get; set; }
    public Emote Clock { get; set; }
}

And define Type Converter when configuring services:
public void ConfigureServices(IServiceCollection services)
{
    TypeDescriptor.AddAttributes(typeof(Emote), new TypeConverterAttribute(typeof(EmotesConverter)));
    services.Configure<EmotesOptions>(Configuration.GetSection("Emotes");
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question