From f17e89b23370bd1c8cf84bdd2a1dae9f6953b626 Mon Sep 17 00:00:00 2001 From: Oleksandr Liakhevych Date: Fri, 21 Mar 2025 18:28:05 +0200 Subject: [PATCH 1/2] Add Options example --- README.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/README.md b/README.md index cb0ef29..c158b8b 100644 --- a/README.md +++ b/README.md @@ -100,7 +100,36 @@ public static partial class ServiceCollectionExtensions T.MapEndpoint(endpoints); } } +``` + +### Register Options types +Another example of `CustomHandler` is to register Options types. We can define custom `OptionAttribute`, which allows to specify configuration section key. +And than read that value in out `CustomHandler`: +```csharp +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] +public class OptionAttribute(string? section = null) : Attribute +{ + public string? Section { get; } = section; +} + +[Option] +public record RootSection { } + +[Option("SectionOption")] +public record SectionOption { } +public static partial class ServiceCollectionExtensions +{ + [GenerateServiceRegistrations(AttributeFilter = typeof(OptionAttribute), CustomHandler = nameof(AddOption))] + public static partial IServiceCollection AddOptions(this IServiceCollection services, IConfiguration configuration); + + private static void AddOption(IServiceCollection services, IConfiguration configuration) where T : class + { + var sectionKey = typeof(T).GetCustomAttribute()?.Section; + var section = sectionKey is null ? configuration : configuration.GetSection(sectionKey); + services.Configure(section); + } +} ``` From 482c090966933224bf9fe1c087f7e776223f85b2 Mon Sep 17 00:00:00 2001 From: Oleksandr Liakhevych Date: Fri, 21 Mar 2025 18:29:24 +0200 Subject: [PATCH 2/2] Update README.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c158b8b..2725923 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ public static partial class ServiceCollectionExtensions ### Register Options types Another example of `CustomHandler` is to register Options types. We can define custom `OptionAttribute`, which allows to specify configuration section key. -And than read that value in out `CustomHandler`: +And then read that value in our `CustomHandler`: ```csharp [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class OptionAttribute(string? section = null) : Attribute