Custom Context Type¶
When the built-in context types do not meet the requirements, you can refer to the implementation of EnvContext to implement your own context type.
How to Implement a Custom Context Type¶
-
Define the context type
public class CustomContext { // The context will be stored as a key-value pair, and this key is the ContextKey public static string ContextKey { get; set; } = "x-custom-context"; public CustomContext(string data) { Data = data; } public string Data { get; private set; } }
-
Implement the
IContextCarrierHandler
interfacepublic class CustomContextCarrierHandler : IContextCarrierHandler { public Type ContextType => typeof(CustomContext); public void Inject(IContextCarrier carrier, object? context) { if (context != null) { carrier.Set(CustomContext.ContextKey, ((CustomContext)context).Data); } } public object? Initial() { return null; } }
-
Implement the
IContextSourceHandler
interfacepublic class CustomContextSourceHandler : IContextSourceHandler { public Type ContextType => typeof(CustomContext); public object? Extract(IContextSource source) { var data = source.Get(CustomContext.ContextKey); return string.IsNullOrEmpty(data) ? null : new CustomContext(data); } }
-
Add context type registration
public static class ServiceCollectionExtensions { public static IServiceCollection AddCustomContext(this IServiceCollection services) { services.AddContextCore(); services.TryAddSingleton<IContextCarrierHandler, CustomContextCarrierHandler>(); services.TryAddSingleton<IContextSourceHandler, CustomContextSourceHandler>(); return services; } }
-
Register the context type in
Program.cs
builder.Services.AddContext() .AddEnvContext() .AddTenantContext() .AddCustomContext() // Add custom context .AddCapContextProcessor();