budul.IdGenerator 1.0.0

dotnet add package budul.IdGenerator --version 1.0.0
                    
NuGet\Install-Package budul.IdGenerator -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="budul.IdGenerator" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="budul.IdGenerator" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="budul.IdGenerator" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add budul.IdGenerator --version 1.0.0
                    
#r "nuget: budul.IdGenerator, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package budul.IdGenerator@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=budul.IdGenerator&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=budul.IdGenerator&version=1.0.0
                    
Install as a Cake Tool

IdGenerator

NuGet License: MIT

A flexible, thread-safe unique identifier generator for .NET applications. This library provides a simple way to generate readable and predictable identifiers as an alternative to GUIDs when human-readability is important.

Features

  • Type-based prefix generation with intelligent string shrinking
  • Custom prefix support
  • Thread-safe implementation
  • Configurable delimiters and formatting
  • Automatic uniqueness handling
  • Clean, readable identifiers

Installation

Install the package via NuGet:

dotnet add package budul.IdGenerator

Or via the NuGet Package Manager:

Install-Package budul.IdGenerator

Usage

Basic Usage

// Create a generator with default settings
var generator = new IdGenerator();

// Generate IDs using type prefixes
string userId = generator.Generate<User>("john");            // "usr_john"
string orderId = generator.Generate<Order>("12345");         // "ordr_12345"
string productId = generator.Generate<Product>("keyboard");  // "prdct_keyboard"

// Automatic uniqueness for duplicate base IDs
string userId1 = generator.Generate<User>("john");           // "usr_john_2" (as "usr_john" was already used)

Using Suffixes

// Add multiple suffixes
string id = generator.Generate<Order>("main", "2023", "Q2"); // "ordr_main_2023_Q2"

Custom Prefix

// Generate IDs with custom prefixes instead of type names
string customId = generator.Generate("custom", "special");   // "custom_special"

Configuration Options

// Configure the generator with custom settings
var customGenerator = new IdGenerator(
    delimiter: "-",            // Use hyphen instead of underscore
    avoidCamelCases: true,      // Don't convert type names to camel case
    typePrefixLength: 6,       // Use up to 6 characters for type prefixes
    invalidCharactersPattern: "[^a-z0-9]+" // Only allow lowercase and numbers
);

string id = customGenerator.Generate<Product>("Gaming Keyboard"); // "produc-gamingkeyboard"

String Shrinking Algorithm

The library includes an intelligent string shrinking algorithm that:

  1. Removes vowels that aren't at the beginning of words
  2. Splits input on non-alphanumeric characters
  3. Proportionally allocates space to each part based on original length
  4. Maintains readability while reducing length

Examples of type prefix shrinking:

"Customer" → "cstmr"
"OrderItem" → "ordrItm"
"ProductCatalog" → "prdctCtlg"
"ShoppingCart" → "shppngCrt"

You can also use the string shrinking functionality directly:

using IdGenerator.Extensions;

string shortened = "ProductDescription".Shrink(maxLength: 8, avoidCamelCases: false);
// Result: "prdctDsc"

Resetting the Generator

// Clear all stored IDs and counters
generator.Reset();

Examples

Entity IDs in a Database Context

public class ApplicationDbContext : DbContext
{
    private readonly IdGenerator _idGenerator = new IdGenerator();
    
    public DbSet<User> Users { get; set; }
    public DbSet<Order> Orders { get; set; }
    
    public override int SaveChanges()
    {
        foreach (var entry in ChangeTracker.Entries())
        {
            if (entry.State == EntityState.Added)
            {
                if (entry.Entity is IEntity entity && string.IsNullOrEmpty(entity.Id))
                {
                    // Generate a unique ID based on the entity type
                    entity.Id = _idGenerator.Generate(entry.Entity.GetType());
                }
            }
        }
        
        return base.SaveChanges();
    }
}

API Resource Identifiers

[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
    private readonly IdGenerator _idGenerator = new IdGenerator();
    private readonly ProductRepository _repository;
    
    public ProductsController(ProductRepository repository)
    {
        _repository = repository;
    }
    
    [HttpPost]
    public IActionResult CreateProduct(ProductDto productDto)
    {
        var product = new Product
        {
            Id = _idGenerator.Generate<Product>(productDto.Name),
            Name = productDto.Name,
            // ...
        };
        
        _repository.Add(product);
        
        return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
    }
    
    [HttpGet("{id}")]
    public IActionResult GetProduct(string id)
    {
        // ...
    }
}

Performance Considerations

The IdGenerator is designed to be efficient and thread-safe. It uses concurrent collections to store identifier counts and used IDs, making it suitable for multi-threaded environments like web servers.

The string shrinking algorithm has been optimized for performance with compiled regex patterns and efficient character allocation.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  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 is compatible.  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 is compatible.  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.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.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 is compatible. 
.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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.
  • .NETStandard 2.1

    • No dependencies.
  • net6.0

    • No dependencies.
  • net7.0

    • No dependencies.
  • net8.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
1.0.0 154 4/10/2025