AltaSoft.DomainPrimitives.Generator
2.2.0
See the version list below for details.
dotnet add package AltaSoft.DomainPrimitives.Generator --version 2.2.0
NuGet\Install-Package AltaSoft.DomainPrimitives.Generator -Version 2.2.0
<PackageReference Include="AltaSoft.DomainPrimitives.Generator" Version="2.2.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
paket add AltaSoft.DomainPrimitives.Generator --version 2.2.0
#r "nuget: AltaSoft.DomainPrimitives.Generator, 2.2.0"
// Install AltaSoft.DomainPrimitives.Generator as a Cake Addin #addin nuget:?package=AltaSoft.DomainPrimitives.Generator&version=2.2.0 // Install AltaSoft.DomainPrimitives.Generator as a Cake Tool #tool nuget:?package=AltaSoft.DomainPrimitives.Generator&version=2.2.0
DomainPrimitives for C#
Table of Contents
- Introduction
- Key Features
- Generator Features
- Supported Underlying types
- Getting Started
- Prerequisites
- Installation
- Creating your Domain type
- Json Conversion
- Contributions
- Contact
- License
Introduction
Welcome to AltaSoft.DomainPrimitives - a C# toolkit purposefully designed to accelerate the development of domain-specific primitives within your applications. This streamlined solution empowers developers to efficiently encapsulate fundamental domain logic. Through this toolkit, you'll significantly reduce code complexity while improving the maintainability of your project.
Key Features
- Simplified Primitive Creation - Utilize source generators to swiftly create domain-specific primitives with ease and precision.
- Versatile Underlying Type Support - Embrace a wide array of underlying types, catering to diverse application requirements.
- Enhanced Code Quality - Create clean, maintainable, and thoroughly testable code through encapsulation and robust design principles.
With AltaSoft.DomainPrimitives
, experience an accelerated development process while upholding code quality standards. This toolkit empowers developers to focus on the core business logic without compromising on precision or efficiency.
Generator Features
The AltaSoft.DomainPrimitives.Generator offers a diverse set of features:
- Implicit Operators: Streamlines type conversion to/from the underlying primitive type. Example
- Specialized Constructor Generation: Automatically validates and constructs instances of this domain type. This constructor, tailored for the domain primitive, utilizes the underlying type as a parameter, ensuring the value's correctness within the domain.
- JsonConverters: Handles JSON serialization and deserialization for the underlying type. Example
- TypeConverters: Assists in type conversion to/from it's underlying type. Please refer to generated type converter below
- Swagger Custom Type Mappings: Facilitates easy integration with Swagger by treating the primitive type as it's underlying type. Please refer to generated swagger helper below
- Interface Implementations: All DomainPritmitives Implement
IConvertible
,IComparable
,IComparable<T>
,IEquatable<T>
,IEqualityComparer<T>
,IParsable
interfaces. - NumberType Operations: Automatically generates basic arithmetic and comparison operators, by implementing Static abstract interfaces. More details regarding numeric types
- IParsable Implementation: Automatically generates parsing for non-string types.
- XML Serialiaziton Generates IXmlSerializable interface implementation, to serialize and deserialize from/to xml.
Supported Underlying types
string
Guid
byte
sbyte
short
ushort
int
uint
long
ulong
decimal
double
float
bool
char
TimeSpan
DateTime
DateTimeOffset
DateOnly
TimeOnly
Getting Started
Prerequisites
- .NET 7 or higher
- NuGet Package Manager
Installation
To use AltaSoft.DomainPrimitives, install two NuGet packages:
AltaSoft.DomainPrimitives
AltaSoft.DomainPrimitives.Generator
In your project file add references as follows:
<ItemGroup>
<PackageReference Include="AltaSoft.DomainPrimitives" Version="x.x.x" />
<PackageReference Include="AltaSoft.DomainPrimitives.Generator" Version="x.x.x" PrivateAssets="all" />
</ItemGroup>
Creating your Domain type
For optimal performance, it is recommended to use readonly struct
, especially when wrapping value types. If the type is a reference
type, consider using class
over struct
.
public readonly partial struct PositiveInteger : IDomainValue<int>
{
public static void Validate(int value)
{
if (value <= 0)
throw new InvalidDomainValueException("Number must be positive");
}
public static int Default => 1;
}
This will automatically generate by default 4 classes
PositiveInteger.Generated
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by 'AltaSoft DomainPrimitives Generator'.
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#nullable enable
using System;
using System.Numerics;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization;
using AltaSoft.DomainPrimitives.XmlDataTypes.Converters;
using System.ComponentModel;
namespace AltaSoft.DomainPrimitives.XmlDataTypes;
[JsonConverter(typeof(PositiveIntegerJsonConverter))]
[TypeConverter(typeof(PositiveIntegerTypeConverter))]
[DebuggerDisplay("{_valueOrDefault}")]
public readonly partial struct PositiveInteger : IEquatable<PositiveInteger>
, IComparable
, IComparable<PositiveInteger>
, IAdditionOperators<PositiveInteger, PositiveInteger, PositiveInteger>
, ISubtractionOperators<PositiveInteger, PositiveInteger, PositiveInteger>
, IMultiplyOperators<PositiveInteger, PositiveInteger, PositiveInteger>
, IDivisionOperators<PositiveInteger, PositiveInteger, PositiveInteger>
, IModulusOperators<PositiveInteger, PositiveInteger, PositiveInteger>
, IComparisonOperators<PositiveInteger, PositiveInteger, bool>
, IParsable<PositiveInteger>
, IConvertible
#if NET8_0_OR_GREATER
, IUtf8SpanFormattable
#endif
{
private int _valueOrDefault => _isInitialized ? _value : Default;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly int _value;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly bool _isInitialized;
/// <summary>
/// Initializes a new instance of the <see cref="PositiveInteger"/> class by validating the specified <see cref="int"/> value using <see cref="Validate"/> static method.
/// </summary>
/// <param name="value">The value to be validated.</param>
public PositiveInteger(int value)
{
Validate(value);
_value = value;
_isInitialized = true;
}
/// <inheritdoc/>
[Obsolete("Domain primitive cannot be created using empty Ctor", true)]
public PositiveInteger()
{
_value = Default;
_isInitialized = true;
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool Equals(object? obj) => obj is PositiveInteger other && Equals(other);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(PositiveInteger other) => _valueOrDefault == other._valueOrDefault;
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(PositiveInteger left, PositiveInteger right) => left.Equals(right);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(PositiveInteger left, PositiveInteger right) => !(left == right);
/// <inheritdoc/>
public int CompareTo(object? obj)
{
if (obj is null)
return 1;
if (obj is PositiveInteger c)
return CompareTo(c);
throw new ArgumentException("Object is not a PositiveInteger", nameof(obj));
}
/// <inheritdoc/>
public int CompareTo(PositiveInteger other) => _valueOrDefault.CompareTo(other._valueOrDefault);
/// <summary>
/// Implicit conversion from <see cref = "int"/> to <see cref = "PositiveInteger"/>
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator PositiveInteger(int value) => new(value);
/// <summary>
/// Implicit conversion from <see cref = "int"/> (nullable) to <see cref = "PositiveInteger"/> (nullable)
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NotNullIfNotNull(nameof(value))]
public static implicit operator PositiveInteger?(int? value) => value is null ? null : new(value.Value);
/// <summary>
/// Implicit conversion from <see cref = "PositiveInteger"/> to <see cref = "int"/>
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator int(PositiveInteger value) => (int)value._valueOrDefault;
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static PositiveInteger operator +(PositiveInteger left, PositiveInteger right) => new(left._valueOrDefault + right._valueOrDefault);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static PositiveInteger operator -(PositiveInteger left, PositiveInteger right) => new(left._valueOrDefault - right._valueOrDefault);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static PositiveInteger operator *(PositiveInteger left, PositiveInteger right) => new(left._valueOrDefault * right._valueOrDefault);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static PositiveInteger operator /(PositiveInteger left, PositiveInteger right) => new(left._valueOrDefault / right._valueOrDefault);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static PositiveInteger operator %(PositiveInteger left, PositiveInteger right) => new(left._valueOrDefault % right._valueOrDefault);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator <(PositiveInteger left, PositiveInteger right) => left._valueOrDefault < right._valueOrDefault;
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator <=(PositiveInteger left, PositiveInteger right) => left._valueOrDefault <= right._valueOrDefault;
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator >(PositiveInteger left, PositiveInteger right) => left._valueOrDefault > right._valueOrDefault;
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator >=(PositiveInteger left, PositiveInteger right) => left._valueOrDefault >= right._valueOrDefault;
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static PositiveInteger Parse(string s, IFormatProvider? provider) => int.Parse(s, provider);
/// <inheritdoc/>
public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, [MaybeNullWhen(false)] out PositiveInteger result)
{
if (!int.TryParse(s, provider, out var value))
{
result = default;
return false;
}
try
{
result = new PositiveInteger(value);
return true;
}
catch (Exception)
{
result = default;
return false;
}
}
#if NET8_0_OR_GREATER
/// <inheritdoc cref="IUtf8SpanFormattable.TryFormat"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryFormat(Span<byte> utf8Destination, out int bytesWritten, ReadOnlySpan<char> format, IFormatProvider? provider)
{
return ((IUtf8SpanFormattable)_valueOrDefault).TryFormat(utf8Destination, out bytesWritten, format, provider);
}
#endif
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode() => _valueOrDefault.GetHashCode();
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
TypeCode IConvertible.GetTypeCode() => ((IConvertible)(Int32)_valueOrDefault).GetTypeCode();
/// <inheritdoc/>
bool IConvertible.ToBoolean(IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToBoolean(provider);
/// <inheritdoc/>
byte IConvertible.ToByte(IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToByte(provider);
/// <inheritdoc/>
char IConvertible.ToChar(IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToChar(provider);
/// <inheritdoc/>
DateTime IConvertible.ToDateTime(IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToDateTime(provider);
/// <inheritdoc/>
decimal IConvertible.ToDecimal(IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToDecimal(provider);
/// <inheritdoc/>
double IConvertible.ToDouble(IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToDouble(provider);
/// <inheritdoc/>
short IConvertible.ToInt16(IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToInt16(provider);
/// <inheritdoc/>
int IConvertible.ToInt32(IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToInt32(provider);
/// <inheritdoc/>
long IConvertible.ToInt64(IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToInt64(provider);
/// <inheritdoc/>
sbyte IConvertible.ToSByte(IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToSByte(provider);
/// <inheritdoc/>
float IConvertible.ToSingle(IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToSingle(provider);
/// <inheritdoc/>
string IConvertible.ToString(IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToString(provider);
/// <inheritdoc/>
object IConvertible.ToType(Type conversionType, IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToType(conversionType, provider);
/// <inheritdoc/>
ushort IConvertible.ToUInt16(IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToUInt16(provider);
/// <inheritdoc/>
uint IConvertible.ToUInt32(IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToUInt32(provider);
/// <inheritdoc/>
ulong IConvertible.ToUInt64(IFormatProvider? provider) => ((IConvertible)(Int32)_valueOrDefault).ToUInt64(provider);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override string ToString() => _valueOrDefault.ToString();
}
JsonConverter
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by 'AltaSoft DomainPrimitives Generator'.
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#nullable enable
using AltaSoft.DomainPrimitives;
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Globalization;
using System.Text.Json.Serialization.Metadata;
namespace AltaSoft.DomainPrimitives.Converters;
/// <summary>
/// JsonConverter for <see cref = "PositiveInteger"/>
/// </summary>
public sealed class PositiveIntegerJsonConverter : JsonConverter<PositiveInteger>
{
/// <inheritdoc/>
public override PositiveInteger Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
try
{
return JsonInternalConverters.Int32Converter.Read(ref reader, typeToConvert, options);
}
catch (InvalidDomainValueException ex)
{
throw new JsonException(ex.Message);
}
}
/// <inheritdoc/>
public override void Write(Utf8JsonWriter writer, PositiveInteger value, JsonSerializerOptions options)
{
JsonInternalConverters.Int32Converter.Write(writer, (int)value, options);
}
/// <inheritdoc/>
public override PositiveInteger ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
try
{
return JsonInternalConverters.Int32Converter.ReadAsPropertyName(ref reader, typeToConvert, options);
}
catch (InvalidDomainValueException ex)
{
throw new JsonException(ex.Message);
}
}
/// <inheritdoc/>
public override void WriteAsPropertyName(Utf8JsonWriter writer, PositiveInteger value, JsonSerializerOptions options)
{
JsonInternalConverters.Int32Converter.WriteAsPropertyName(writer, (int)value, options);
}
}
Type Converter
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by 'AltaSoft DomainPrimitives Generator'.
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#nullable enable
using AltaSoft.DomainPrimitives;
using System;
using System.ComponentModel;
using System.Globalization;
namespace AltaSoft.DomainPrimitives.Converters;
/// <summary>
/// TypeConverter for <see cref = "PositiveInteger"/>
/// </summary>
public sealed class PositiveIntegerTypeConverter : Int32Converter
{
/// <inheritdoc/>
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
{
var result = base.ConvertFrom(context, culture, value);
if (result is null)
return null;
try
{
return new PositiveInteger((int)result);
}
catch (InvalidDomainValueException ex)
{
throw new FormatException("Cannot parse PositiveInteger", ex);
}
}
}
Swagger Mappers
A single file for all domainPrimitives containing all type mappings is generated.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by 'AltaSoft DomainPrimitives Generator'.
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#nullable enable
using AltaSoft.DomainPrimitives;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.OpenApi.Models;
namespace AltaSoft.DomainPrimitives.Converters.Extensions;
/// <summary>
/// Helper class providing methods to configure Swagger mappings for DomainPrimitive types of AltaSoft.DomainPrimitives
/// </summary>
public static class SwaggerTypeHelper
{
/// <summary>
/// Adds Swagger mappings for specific custom types to ensure proper OpenAPI documentation generation.
/// </summary>
/// <param name="options">The SwaggerGenOptions instance to which mappings are added.</param>
/// <remarks>
/// The method adds Swagger mappings for the following types:
/// <see cref="PositiveInteger"/>
/// </remarks>
public static void AddSwaggerMappings(this SwaggerGenOptions options)
{
options.MapType<PositiveInteger>(() => new OpenApiSchema
{
Type = "integer",
Format = "int32",
Title = "PositiveInteger",
Default = new OpenApiInteger(PositiveInteger.Default),
Description = @"A domain primitive type representing a positive integer."
});
options.MapType<PositiveInteger?>(() => new OpenApiSchema
{
Type = "integer",
Format = "int32",
Nullable = true,
Title = "Nullable<PositiveInteger>",
Default = new OpenApiInteger(PositiveInteger.Default),
Description = @"A domain primitive type representing a positive integer."
});
}
}
Specialized ToString method
By Default IDomainValue uses its underlying type's ToString method however this can be overriden by implementing a method specified below
static virtual string ToString(T value) => value.ToString() ?? string.Empty;
Managing Generated Operators for numeric types
Mathematical operators for particular numeric types can be customized using the SupportedOperationsAttribute
. If left unspecified, all operators are generated by default (as shown below). Once this attribute is applied, manual specification of the operators becomes mandatory. Note that for byte
, sbyte
, short
, and ushort
types, mathematical operators will not be generated by default.
Default numeric types Generated Operators
byte, sbyte
⇒None
short, ushort
⇒None
int, uint
⇒+ - / * %
long, ulong
⇒+ - / * %
double
⇒+ - / * %
decimal
⇒+ - / * %
using SupportedOperationsAttribute
[SupportedOperations(Addition = false, Division = false, Modulus = false, Multiplication = true, Subtraction = true)]
public readonly partial struct PositiveInteger : IDomainValue<int>
{
public static void Validate(int value)
{
if (value <= 0)
throw new InvalidDomainValueException("Number must be positive");
}
public static int Default => 1;
}
For further customization of the operators, consider implementing specific interfaces. This action will override the generated operators for the respective domain type:
public readonly partial struct PositiveInteger :
IDomainValue<int>,
IAdditionOperators<PositiveInteger, PositiveInteger, PositiveInteger>
{
public static void Validate(int value)
{
if (value <= 0)
throw new InvalidDomainValueException("Number must be positive");
}
public static int Default => 1;
// custom + operator
public static PositiveInteger operator +(PositiveInteger left, PositiveInteger right)
{
return (left._value + right._value + 1);
}
}
Managing Serialization Format for date-related types
Certain date-related types like DateTime
, DateOnly
, TimeOnly
, DateTimeOffset
, and TimeSpan
can modify their serialization/deserialization format using the SerializationFormatAttribute
.
For instance, consider the GDay
type, which represents an XML gDay value. It implements the IDomainValue<DateOnly>
interface and utilizes the SerializationFormatAttribute
to specify a serialization format.
/// <summary>
/// Represents an XML gDay value object, providing operations for parsing and handling gDay values.
/// </summary>
[SerializationFormat("dd")]
public readonly partial struct GDay : IDomainValue<DateOnly>
{
/// <inheritdoc/>
public static void Validate(DateOnly value)
{ }
/// <inheritdoc/>
public static DateOnly Default => default;
// Customized string representation of DateOnly
/// <inheritdoc/>
public static string ToString(DateOnly value) => value.ToString("dd");
}
Disable Generation of Converters
To disable the generation of Converters, Swagger Mappers or XML serialization, in .csproj file follow the below described steps.
<PropertyGroup>
<DomainPrimitiveGenerator_GenerateJsonConverters>false</DomainPrimitiveGenerator_GenerateJsonConverters>
<DomainPrimitiveGenerator_GenerateTypeConverters>false</DomainPrimitiveGenerator_GenerateTypeConverters>
<DomainPrimitiveGenerator_GenerateSwaggerConverters>false</DomainPrimitiveGenerator_GenerateSwaggerConverters>
<DomainPrimitiveGenerator_GenerateXmlSerialization>false</DomainPrimitiveGenerator_GenerateXmlSerialization>
</PropertyGroup>
⚠️ Please note that DomainPrimitiveGenerator_GenerateXmlSerialization
value by default is false
.
Additional Features
Handling Domain Value Exception
- To ensure correct error handling, it's recommended to throw
InvalidDomainValueException
or (descendants ofInvalidDomainValueException
) provided inAltaSoft.DomainPrimitives
. This exception, when thrown fromJsonConverter
orTypeConverter
, will be converted toBadRequest
. Using any other exception in theValidate
method will prompt a compiler warning.
- To ensure correct error handling, it's recommended to throw
Chaining Primitive Types
- Chaining of primitive types is possible. For instance, considering the
PositiveInteger
andBetweenOneAnd100
DomainPrimitives:
public readonly partial struct PositiveInteger : IDomainValue<int> { public static void Validate(int value) { if (value <= 0) throw new InvalidDomainValueException("Number must be positive"); } public static int Default => 1; } public readonly partial struct BetweenOneAnd100 : IDomainValue<PositiveInteger> { public static void Validate(PositiveInteger value) { if (value < 100) throw new InvalidDomainValueException("Value must be less than 100"); } public static PositiveInteger Default => 1; // using implicit operators this is possible. }
- Chaining of primitive types is possible. For instance, considering the
Defined type
BetweenOneAnd100
automatically inherits restrictions from PositiveInteger. Operators restricted in PositiveInteger are also inherited. Further restrictions on operators can be added using theSupportedOperationsAttribute
:-
[SupportedOperations(Addition=false)] public readonly partial struct BetweenOneAnd100 : IDomainValue<PositiveInteger> { public static void Validate(PositiveInteger value) { if (value < 100) throw new InvalidDomainValueException("Value must be less than 100"); } public static PositiveInteger Default => 1; // using implicit operators this is possible. }
Default Value Guarantee with IDomainValue<T>
IDomainValue<T>
incorporates a static abstract property Default to ensure the correct domain state if a value is uninitialized. For example:
public class TestObject { public PositiveInteger CustomerId { get; set; } } public class Program { var test = new TestObject(); Console.Write(test); // If no Default was defined, CustomerId would default to 0, providing invalid value in the Domain. Providing a Default value ensures initialization according to validation rules by initializing in this example to 1 . }
These additional features offer enhanced control over exceptions, chaining of primitive types, inheritance of restrictions and operators, and a mechanism to ensure correct default values within the domain.
Restrictions
Implementation of IDomainValue Interface
- DomainPrimitives are mandated to implement the
IDomainValue<T>
interface to ensure adherence to domain-specific constraints and behaviors.
- DomainPrimitives are mandated to implement the
Constructor Limitation
- No constructors should be explicitly defined within DomainPrimitives. Doing so will result in a compiler error.
Prohibition of Public Properties or Fields
- DomainPrimitive types should not contain any explicitly defined public properties or fields. The backing field will be automatically generated.
- If any property or field is explicitly named
_value
,_valueOrDefault
, or_isInitialized
, a compiler error will be triggered.
- If any property or field is explicitly named
- DomainPrimitive types should not contain any explicitly defined public properties or fields. The backing field will be automatically generated.
Examples
Implicit Usage of DomainType
public readonly partial struct PositiveAmount : IDomainValue<decimal>
{
public static void Validate(decimal value)
{
if (value <= 0m)
throw new InvalidDomainValueException("Must be a a positive number");
}
public static decimal Default => 1m;
}
public static class Example
{
public static void ImplicitConversion()
{
var amount = new PositiveAmount(100m);
PositiveAmount amount2 = 100m; // implicitly converted to PositiveAmount
//implicilty casted to decimal
decimal amountInDecimal = amount + amount2;
}
}
Json Conversion
[SupportedOperations] // no mathematical operators should be generated
public readonly partial struct CustomerId : IDomainValue<int>
{
public static void Validate(int value)
{
if (value <= 0)
throw new InvalidDomainValueException("Value must be a positive number");
}
public static int Default => 1;
}
public sealed class Transaction
{
public CustomerId FromId { get; set; }
public CustomerId? ToId { get; set; }
public PositiveAmount Amount { get; set; }
public PositiveAmount? Fees { get; set; }
}
public static void JsonSerializationAndDeserialization()
{
var amount = new Transaction()
{
Amount = 100.523m,
Fees = null,
FromId = 1,
ToId = null
};
var jsonValue = JsonSerializer.Serialize(amount); //this will produce the same result as changing customerId to int and PositiveAmount to decimal
var newValue = JsonSerializer.Deserialize<Transaction>(jsonValue)
}
Serialized Json
{
"FromId": 1,
"ToId": null,
"Amount": 100.523,
"Fees": null
}
Contributions
Contributions to AltaSoft.DomainPrimitives are welcome! Whether you have suggestions or wish to contribute code, feel free to submit a pull request or open an issue.
Contact
For support, questions, or additional information, please visit GitHub Issues.
License
This project is licensed under MIT. See the LICENSE file for details.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
.NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
.NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
MonoAndroid | monoandroid was computed. |
MonoMac | monomac was computed. |
MonoTouch | monotouch was computed. |
Tizen | tizen40 was computed. tizen60 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last updated | |
---|---|---|---|
5.0.0 | 46 | 11/21/2024 | |
4.2.0 | 368 | 9/5/2024 | |
4.1.0 | 192 | 6/18/2024 | |
4.0.0 | 109 | 6/3/2024 | |
3.0.1 | 177 | 5/7/2024 | |
3.0.0 | 101 | 5/1/2024 | |
2.2.3 | 281 | 4/4/2024 | |
2.2.1 | 114 | 4/4/2024 | |
2.2.0 | 119 | 4/4/2024 | |
2.1.0 | 126 | 3/18/2024 | |
2.0.4 | 147 | 3/13/2024 | |
2.0.3 | 131 | 3/11/2024 | |
2.0.2 | 102 | 3/11/2024 | |
2.0.1 | 143 | 2/7/2024 | |
2.0.0 | 159 | 1/22/2024 | |
1.0.4 | 216 | 1/10/2024 |