Microsoft.Extensions.Options.Generators.OptionsValidatorGenerator by Microsoft
Nuget / site data
Details
Info
Name: Microsoft.Extensions.Options.Generators.OptionsValidatorGenerator
Microsoft.Extensions.Options
Author: Microsoft
NuGet: https://www.nuget.org/packages/Microsoft.Extensions.Options
You can find more details at https://learn.microsoft.com/en-us/dotnet/core/extensions/options-validation-generator
Source : https://github.com/dotnet/runtime
Original Readme
.NET Runtime
- What is .NET?
- How can I contribute?
- Reporting security issues and security bugs
- Filing issues
- Useful Links
- .NET Foundation
- License
This repo contains the code to build the .NET runtime, libraries and shared host (dotnet
) installers for
all supported platforms, as well as the sources to .NET runtime and libraries.
What is .NET?
Official Starting Page: https://dotnet.microsoft.com
- How to use .NET (with VS, VS Code, command-line CLI)
- Install official releases
- Documentation (Get Started, Tutorials, Porting from .NET Framework, API reference, ...)
- Supported OS versions
- Roadmap
- Releases
How can I contribute?
We welcome contributions! Many people all over the world have helped make this project better.
Reporting security issues and security bugs
Security issues and bugs should be reported privately, via email, to the Microsoft Security Response Center (MSRC) secure@microsoft.com. You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Further information, including the MSRC PGP key, can be found in the Security TechCenter. You can also find these instructions in this repo's Security doc.
Also see info about related Microsoft .NET Core and ASP.NET Core Bug Bounty Program.
Filing issues
This repo should contain issues that are tied to the runtime, the class libraries and frameworks, the installation of the dotnet
binary (sometimes known as the muxer
) and the installation of the .NET runtime and libraries.
For other issues, please file them to their appropriate sibling repos. We have links to many of them on our new issue page.
Useful Links
- .NET Core source index / .NET Framework source index
- API Reference docs
- .NET API Catalog (incl. APIs from daily builds and API usage info)
- API docs writing guidelines - useful when writing /// comments
- .NET Discord Server - a place to discuss the development of .NET and its ecosystem
.NET Foundation
.NET Runtime is a .NET Foundation project.
There are many .NET related projects on GitHub.
- .NET home repo - links to 100s of .NET projects, from Microsoft and the community.
- ASP.NET Core home - the best place to start learning about ASP.NET Core.
This project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behavior in our community. For more information, see the .NET Foundation Code of Conduct.
General .NET OSS discussions: .NET Foundation Discussions
License
.NET (including the runtime repo) is licensed under the MIT license.
About
Generating the validation for data annotations on options classes.
How to use
Example ( source csproj, source files )
- CSharp Project
- MyAppValidator.cs
- MyAppOptions.cs
This is the CSharp Project that references Microsoft.Extensions.Options.Generators.OptionsValidatorGenerator
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.0" />
</ItemGroup>
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
</Project>
This is the use of Microsoft.Extensions.Options.Generators.OptionsValidatorGenerator in MyAppValidator.cs
namespace DemoValidatorObj;
[OptionsValidator]
public partial class ValidatorForMyApp
: IValidateOptions<MyAppOptions>
{
}
//public class SecondModelNoNamespace
//{
// [Required]
// [MinLength(5)]
// public string P4 { get; set; } = string.Empty;
//}
//[OptionsValidator]
//public partial class SecondValidatorNoNamespace
// : IValidateOptions<SecondModelNoNamespace>
//{
//}
This is the use of Microsoft.Extensions.Options.Generators.OptionsValidatorGenerator in MyAppOptions.cs
namespace DemoValidatorObj;
[DebuggerDisplay("{AppDisplayName}")]
public class MyAppOptions
{
public const string ConfigName = "MyAppOptionsInConfig";
[Required]
[MinLength(3)]
public string AppDisplayName { get; set; } = string.Empty;
//[ValidateObjectMembers(
// typeof(SecondValidatorNoNamespace))]
//public SecondModelNoNamespace? P2 { get; set; }
}
//[OptionsValidator]
//public partial class SecondValidatorNoNamespace
// : IValidateOptions<SecondModelNoNamespace>
//{
//}
Generated Files
Those are taken from $(BaseIntermediateOutputPath)\GX
- Validators.g.cs
// <auto-generated/>
#nullable enable
#pragma warning disable CS1591 // Compensate for https://github.com/dotnet/roslyn/issues/54103
namespace DemoValidatorObj
{
partial class ValidatorForMyApp
{
/// <summary>
/// Validates a specific named options instance (or all when <paramref name="name"/> is <see langword="null" />).
/// </summary>
/// <param name="name">The name of the options instance being validated.</param>
/// <param name="options">The options instance.</param>
/// <returns>Validation result.</returns>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Options.SourceGeneration", "8.0.9.3103")]
[System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming", "IL2026:RequiresUnreferencedCode",
Justification = "The created ValidationContext object is used in a way that never call reflection")]
public global::Microsoft.Extensions.Options.ValidateOptionsResult Validate(string? name, global::DemoValidatorObj.MyAppOptions options)
{
global::Microsoft.Extensions.Options.ValidateOptionsResultBuilder? builder = null;
var context = new global::System.ComponentModel.DataAnnotations.ValidationContext(options);
var validationResults = new global::System.Collections.Generic.List<global::System.ComponentModel.DataAnnotations.ValidationResult>();
var validationAttributes = new global::System.Collections.Generic.List<global::System.ComponentModel.DataAnnotations.ValidationAttribute>(2);
context.MemberName = "AppDisplayName";
context.DisplayName = string.IsNullOrEmpty(name) ? "MyAppOptions.AppDisplayName" : $"{name}.AppDisplayName";
validationAttributes.Add(global::__OptionValidationStaticInstances.__Attributes.A1);
validationAttributes.Add(global::__OptionValidationStaticInstances.__Attributes.A2);
if (!global::System.ComponentModel.DataAnnotations.Validator.TryValidateValue(options.AppDisplayName, context, validationResults, validationAttributes))
{
(builder ??= new()).AddResults(validationResults);
}
return builder is null ? global::Microsoft.Extensions.Options.ValidateOptionsResult.Success : builder.Build();
}
}
}
namespace __OptionValidationStaticInstances
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Options.SourceGeneration", "8.0.9.3103")]
file static class __Attributes
{
internal static readonly global::System.ComponentModel.DataAnnotations.RequiredAttribute A1 = new global::System.ComponentModel.DataAnnotations.RequiredAttribute();
internal static readonly __OptionValidationGeneratedAttributes.__SourceGen__MinLengthAttribute A2 = new __OptionValidationGeneratedAttributes.__SourceGen__MinLengthAttribute(
(int)3);
}
}
namespace __OptionValidationStaticInstances
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Options.SourceGeneration", "8.0.9.3103")]
file static class __Validators
{
}
}
namespace __OptionValidationGeneratedAttributes
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Options.SourceGeneration", "8.0.9.3103")]
[global::System.AttributeUsage(global::System.AttributeTargets.Property | global::System.AttributeTargets.Field | global::System.AttributeTargets.Parameter, AllowMultiple = false)]
file class __SourceGen__MinLengthAttribute : global::System.ComponentModel.DataAnnotations.ValidationAttribute
{
private static string DefaultErrorMessageString => "The field {0} must be a string or array type with a minimum length of '{1}'.";
public __SourceGen__MinLengthAttribute(int length) : base(() => DefaultErrorMessageString) { Length = length; }
public int Length { get; }
public override bool IsValid(object? value)
{
if (Length < -1)
{
throw new global::System.InvalidOperationException("MinLengthAttribute must have a Length value that is zero or greater.");
}
if (value == null)
{
return true;
}
int length;
if (value is string stringValue)
{
length = stringValue.Length;
}
else if (value is System.Collections.ICollection collectionValue)
{
length = collectionValue.Count;
}
else
{
throw new global::System.InvalidCastException($"The field of type {value.GetType()} must be a string, array, or ICollection type.");
}
return length >= Length;
}
public override string FormatErrorMessage(string name) => string.Format(global::System.Globalization.CultureInfo.CurrentCulture, ErrorMessageString, name, Length);
}
}