Model binding, JSON serialization and Swagger bindings for AppConstant
$ dotnet add package AppConstant.AspNetCoreAppConstant is a simple type-safe constant* library for C# and ASP.NET Core. It allows you to define type-safe constants that translates to web and database friendly values.
* technically not a constant
To define a constant, you need to create a class that inherits from AppConstant<TConst, TValue>.
The first type parameter is the type of the constant itself, and the second type parameter is the type of the value that the constant represents.
public class MediaType : AppConstant<MediaType, string>
{
public static MediaType Image => Set("image");
public static MediaType Video => Set("video");
public static MediaType Audio => Set("audio");
}
To use a constant, just use the static property that is defined on the constant class.
var image = MediaType.Image;
To use a constant on an entity, you need to define a property of the constant type.
public class Media
{
public int Id { get; set; }
public string Name { get; set; }
public MediaType Type { get; set; }
}
To use AppConstant with ASP.NET Core, you need to register the AppConstant service after the AddControllers method.
builder.Services.AddControllers().AddAppConstant();
If your constants are defined in a different assembly, you can specify that assembly as well.
builder.Services.AddControllers().AddAppConstant(typeof(MediaType).Assembly);
To use AppConstant with Entity Framework Core, you need to register the AppConstant in the ConfigureConventions override method in the DbContext.
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
configurationBuilder.AddAppConstantConverters();
}
Having worked on a few projects where constants were used, I've noticed that there are a few problems with them:
The package is heavily inspired by the SmartEnum package by ardalis. A lot of implementation details are used from that package.