A super small library for providing strong typed Ids (as opposed to using primitives).
The benefit of this is simple: You don't run the risk of accidentally using the wrong type of id. (e.g. sending a UserId into a query for products)
This works through the use of an abstract base class (StrongTypedId<TStrongTypedId, TPrimitiveId>) which is inherited
to gain the id functionality.
This project is inspired by Andrew Lock's StronglyTypedId. However I needed support for .Net 5 and thus this project was born. It has since evolved to .Net 9.
I recommend using the NuGet package: StrongTypedId however feel free to clone the source instead if that suits your needs better.
Specify your class like this:
[StrongTypedValueJsonConverterFactory]
public class UserId: StrongTypedId<UserId, Guid>
{
public UserId(Guid value) : base(value)
{
}
}
This specifies that the class UserId is in fact a Guid and can be used in place of a Guid.
And that's basically all there is to it, now you just use UserId in place of Guid where you're dealing with an User'
s Id.
You can omit the JsonConverter if you don't use json serialization.
Furthermore there are a couple of base classes available to you:
StrongTypedValuefor anything that's not an id, this supportsstringas a primitive value.StrongTypedIdfor anything that IS an id, this only supportsstructtypes as primitives (therefore nostrings).- Adds the static
Parse(string)andTryParse(string, out TStrongTypedId)methods.
- Adds the static
StrongTypedGuida further specialization ofStrongTypedId.- Adds the static
New()method for instantiating new ids with random values as well as the staticEmptyproperty.
- Adds the static
Finally you can recognize a StrongTyped value by calling the extension method IsStrongTypedValue(). All strong typed
values furthermore implements both IStrongTypedValue<TPrimitiveValue> as well as IStrongTypedValue (The latter being
strictly a marker interface).
Auto generated documentation via DocFx is available here: https://steffenskov.github.io/StrongTypedId/
This can work without any extensions, however it's a bit simpler to use via the package StrongTypedId.Dapper.DDD.Repository.
This is supported through the package StrongTypedId.EntityFrameworkCore.
This is supported through the package StrongTypedId.LiteDB.
This is supported through the package StrongTypedId.MongoDB.
This is supported through the use of the built-in JsonConverter.
This is supported out-of-the-box.
This is supported through the package StrongTypedId.NewtonSoft.
This is supported through the package StrongTypedId.Swagger.