Dot.Conductor 1.4.0

dotnet add package Dot.Conductor --version 1.4.0                
NuGet\Install-Package Dot.Conductor -Version 1.4.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="Dot.Conductor" Version="1.4.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Dot.Conductor --version 1.4.0                
#r "nuget: Dot.Conductor, 1.4.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.
// Install Dot.Conductor as a Cake Addin
#addin nuget:?package=Dot.Conductor&version=1.4.0

// Install Dot.Conductor as a Cake Tool
#tool nuget:?package=Dot.Conductor&version=1.4.0                

Unit of Work and Repository Pattern with Entity Framework Core

This library provides an implementation of the Unit of Work (UoW) and Repository pattern using Entity Framework (EF) Core, with support for multi-tenancy and temporal tables.

Features

  • Unit of Work pattern implementation
    • Generic Repository pattern
    • Multi-tenancy support
    • Temporal table querying support
    • Customizable database context configuration
    • Paged results for efficient data retrieval
    • Transaction management
    • Stored procedures support

Setting Up

Basic Setup

In your Startup.cs or Program.cs (for .NET 6+), register the UnitOfWork and repositories using the provided extension method:

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddUnitOfWorkAndRepositories<MyDbContext>(
        Configuration.GetConnectionString("DefaultConnection"),
        sqlOptions => {
            // Configure SQL options if needed
        },
        isDevelopment: Environment.IsDevelopment()
    );

    // ...
}

Multi-tenant Setup

For multi-tenant applications, use the following setup:

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddMultiTenantUnitOfWorkAndRepositories<MyDbContext>(
        sqlOptions => {
            // Configure SQL options if needed
        },
        isDevelopment: Environment.IsDevelopment()
    );

    // Register your tenant strategy
    services.AddScoped<ITenantStrategy, YourTenantStrategyImplementation>();

    // ...
}

Make sure to implement the ITenantStrategy interface to provide tenant-specific connection strings:

public class YourTenantStrategyImplementation : ITenantStrategy
{
    public Task<string> GetTenantIdentifierAsync()
    {
        // Implement logic to get the current tenant identifier
    }

    public Task<string> GetConnectionStringAsync(string tenantIdentifier)
    {
        // Implement logic to get the connection string for the given tenant
    }
}

Using Unit of Work

In Controllers or Services

Inject IUnitOfWork<MyDbContext> in your controller or service constructor:

public class UserController : ControllerBase
{
    private readonly IUnitOfWork<MyDbContext> _unitOfWork;

    public UserController(IUnitOfWork<MyDbContext> unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    // ...
}

Querying Data

public async Task<IActionResult> GetUser(int id)
{
    var userRepository = _unitOfWork.GetRepository<User>();
    var user = await userRepository.GetByIdAsync(id);

    if (user == null)
    {
        return NotFound();
    }

    return Ok(user);
}

Modifying Data

public async Task<IActionResult> UpdateUser(User user)
{
    var userRepository = _unitOfWork.GetRepository<User>();
    await userRepository.UpdateAsync(user);
    await _unitOfWork.CommitAsync();

    return Ok(user);
}

Using Transactions

public async Task<IActionResult> TransferFunds(int fromUserId, int toUserId, decimal amount)
{
    try
    {
        await _unitOfWork.BeginTransactionAsync();

        var userRepository = _unitOfWork.GetRepository<User>();
        
        var fromUser = await userRepository.GetByIdAsync(fromUserId);
        var toUser = await userRepository.GetByIdAsync(toUserId);

        fromUser.Balance -= amount;
        toUser.Balance += amount;

        await userRepository.UpdateAsync(fromUser);
        await userRepository.UpdateAsync(toUser);

        await _unitOfWork.CommitTransactionAsync();

        return Ok("Transfer successful");
    }
    catch (Exception)
    {
        await _unitOfWork.RollbackTransactionAsync();
        return BadRequest("Transfer failed");
    }
}

Paged Results

public async Task<IActionResult> GetUsers(int pageNumber, int pageSize)
{
    var userRepository = _unitOfWork.GetRepository<User>();
    var pagedUsers = await userRepository.GetPagedDataAsync(
        pageNumber,
        pageSize,
        u => u.LastName
    );

    return Ok(pagedUsers);
}

Temporal Queries

Entity Framework Core supports querying temporal tables, allowing you to retrieve data as it existed at a specific point in time or over a range of time. This library extends the repository pattern to include methods for temporal querying.

Enabling Temporal Tables

First, ensure that your entities are configured to use temporal tables in your DbContext:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<User>(entity =>
    {
        entity.ToTable("Users", b => b.IsTemporal());
    });

    // Repeat for other entities as needed...
}
Temporal Query Methods

The repository interface includes the following temporal query methods:

  • TemporalAll(): Retrieves all historical versions of the entity.
  • TemporalAsOf(DateTime dateTime): Retrieves the data as it existed at a specific point in time.
  • TemporalBetween(DateTime from, DateTime to): Retrieves the data that changed between two points in time.
  • TemporalFromTo(DateTime from, DateTime to): Retrieves the data from a specific start time to an end time (exclusive).
Examples
public async Task<IActionResult> GetUserHistory(int userId)
{
    var userRepository = _unitOfWork.GetRepository<User>();

    // Get all historical data for the user
    var userHistory = await userRepository
        .TemporalAll()
        .Where(u => u.Id == userId)
        .ToListAsync();

    return Ok(userHistory);
}

public async Task<IActionResult> GetUserAsOf(int userId, DateTime dateTime)
{
    var userRepository = _unitOfWork.GetRepository<User>();

    // Get user data as of a specific date
    var userAsOf = await userRepository
        .TemporalAsOf(dateTime)
        .FirstOrDefaultAsync(u => u.Id == userId);

    if (userAsOf == null)
    {
        return NotFound();
    }

    return Ok(userAsOf);
}

public async Task<IActionResult> GetUserChanges(int userId, DateTime from, DateTime to)
{
    var userRepository = _unitOfWork.GetRepository<User>();

    // Get user changes between two dates
    var userChanges = await userRepository
        .TemporalBetween(from, to)
        .Where(u => u.Id == userId)
        .ToListAsync();

    return Ok(userChanges);
}

Using Unit of Work Outside of Scope

To use UnitOfWork outside of the default scope, use the extension method provided for IServiceScopeFactory:

public async Task<bool> PerformUnitOfWorkAsync(IServiceScopeFactory scopeFactory)
{
    var result = await scopeFactory.UseUnitOfWork<MyDbContext, bool>("YourConnectionString", async uow =>
    {
        var userRepository = uow.GetRepository<User>();
        var user = new User { Name = "John Doe", Email = "john@example.com" };
        await userRepository.AddAsync(user);
        await uow.CommitAsync();
        return true;
    });

    return result;
}

Notes

  • Lifecycle Management: The implementation handles proper disposal of resources and manages the lifecycle of the DbContext.
  • Multi-tenancy: For multi-tenant scenarios, ensure that your ITenantStrategy implementation correctly identifies tenants and provides the appropriate connection strings.
  • Stored Procedures: The library includes support for stored procedures through the GetStoredProcedures<TProcedures>() method, but you need to implement the procedures class yourself.
  • Development Mode: In development mode, the library enables sensitive data logging, detailed errors, and console logging for the DbContext.
  • Temporal Tables: When using temporal tables, make sure your database supports them and that they are properly configured in your entity mappings.

Contributing

Contributions to improve the library are welcome. Please submit issues and pull requests on the project's repository.

License

MIT License

Copyright (c) [2024]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

Product Compatible and additional computed target framework versions.
.NET 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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.4.0 168 10/17/2024
1.3.0 540 6/23/2024
1.2.23 351 3/11/2024
1.2.22 365 12/29/2023
1.2.21 132 12/29/2023
1.2.20 139 12/28/2023
1.2.19 141 12/19/2023
1.2.18 111 12/19/2023
1.2.17 107 12/19/2023
1.2.16 257 11/15/2023
1.2.15 157 11/5/2023
1.2.14 137 11/4/2023
1.2.13 116 11/4/2023
1.2.12 107 11/4/2023
1.2.11 116 11/4/2023
1.2.10 115 11/4/2023
1.2.9 120 11/4/2023
1.2.8 127 11/4/2023
1.2.7 122 11/2/2023
1.2.6 120 11/2/2023
1.2.5 143 11/2/2023
1.2.4 133 11/2/2023
1.2.3 130 11/1/2023
1.2.2 119 11/1/2023
1.2.1 133 10/27/2023
1.2.0 132 10/27/2023
1.1.1 121 10/25/2023
1.1.0 129 10/19/2023