Microservice.Api 1.0.23

dotnet add package Microservice.Api --version 1.0.23
                    
NuGet\Install-Package Microservice.Api -Version 1.0.23
                    
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="Microservice.Api" Version="1.0.23" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Microservice.Api" Version="1.0.23" />
                    
Directory.Packages.props
<PackageReference Include="Microservice.Api" />
                    
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 Microservice.Api --version 1.0.23
                    
#r "nuget: Microservice.Api, 1.0.23"
                    
#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 Microservice.Api@1.0.23
                    
#: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=Microservice.Api&version=1.0.23
                    
Install as a Cake Addin
#tool nuget:?package=Microservice.Api&version=1.0.23
                    
Install as a Cake Tool

About

Microservice.Api is a .NET library that provides a set of common services and utilities for building microservices. It includes features such as logging, configuration management, dependency injection, and more.

How to Use

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMicroservice();

var app = builder.Build();
app.UseMicroservice();

app.Run();

To create a role provider, you can implement the IRoleProvider interface and define your methods for retrieving roles. Here's an example of a role provider that retrieves roles from a database and caches them using a hybrid cache:

  1. On app startup, the application scans the request handler and automatically registers it.
  2. Middleware scans the role provider to retrieve roles for a given user ID and adds them to the claims.
  3. Role provider used for authentication and authorization in the microservice. It retrieves roles from a database and caches them using a hybrid cache.
  4. Microservice.Security namespace provides the necessary interfaces and classes for implementing role providers.
using Microservice.Security;

class DbRoleProvider(HybridCache cache): CachedRoleProvider("DB role provider", cache) {
	protected Task<IReadOnlyCollection<string>> GetRolesAsync(string? userId, CancellationToken cancellationToken = default) {
		return Task.FromResult<IReadOnlyCollection<string>>(new List<string> { "Admin", "User" });
	}
}

Create entity

using Microservice.Data;

[Database(DatabaseProvider.PostgreSql, ConnectionName = "DefaultConnection")]
public class MyEntity : IEntity<Guid>
{
	[Key(IsAutoGenerated = true)]
	public Guid Id { get; set; }
    public string Name { get; set; } = null!;
    public string? Description { get; set; }
	[CreatedBy]
    public Guid? CreatedBy { get; set; }
    [CreatedAt]
    public DateTime CreatedAt { get; set; }
    [LastModifiedBy]
    public Guid? LastModifiedBy { get; set; }
    [LastModifiedAt]
    public DateTime LastModifiedAt { get; set; }
    [DeletedBy]
    public Guid? DeletedBy { get; set; }
    [DeletedAt]
    public DateTime? DeletedAt { get; set; }
}

To create a request handler, you can implement the IRequestHandler interface and define your methods for handling requests. Here's an example of a request handler that uses a repository factory to perform search and add operations:

  1. On app startup, the application scans the request handler and automatically registers it.
  2. The request handler is responsible for processing incoming requests and returning appropriate responses.
using Microservice.Api;
using Microservice.Data;
using Microservice.Models;

class MyRequestHandler(IRepositoryFactory repositoryFactory) : IRequestHandler
{
	public async Task<SearchResult<MyModel>> SearchAsync(Searchable request, CancellationToken cancellationToken)
	{
        var repos = repositoryFactory.Create<MyEntity, Guid>();
		var results = await repos.SearchAsync<MyModel>(request, cancellationToken: cancellationToken);
		return results;
	}

	public async Task<Guid> AddAsync(MyFormModel request, CancellationToken cancellationToken)
	{
        var repos = repositoryFactory.Create<MyEntity, Guid>();
		var id = await repos.AddAsync<MyModel>(request, cancellationToken: cancellationToken);
		return id;
	}
}

To create an endpoint, you can implement the IEndpoint interface and define your routes and handlers. Here's an example of an endpoint that maps a GET request to a search method and a POST request to an add method:

  1. On app startup, the application scans the endpoint and automatically registers it.
using Microservice.Api;

class MyEndpoint : IEndpoint
{
    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        app.MapPost("/my-endpoint/search", (Searchable request, MyRequestHandler handler, CancellationToken cancellationToken) => handler.Me(request, cancellationToken));
        app.MapPost("/my-endpoint", (MyFormModel request, MyRequestHandler handler, CancellationToken cancellationToken) => handler.AddAsync(request, cancellationToken)).RequireAuthorization();
    }
}

To create a model validator, you can implement the AbstractValidator<T> class from the FluentValidation library and define your validation rules. Here's an example of a model validator that validates a form model:

  1. On app startup, the application scans the model validator and automatically registers it.
  2. The model validator is responsible for validating incoming requests and returning appropriate error messages.
class MyFormModelValidator : AbstractValidator<MyFormModel>
{
	public MyFormModelValidator()
	{
		RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required.");
		RuleFor(x => x.Age).GreaterThan(0).WithMessage("Age must be greater than 0.");
	}
}

To using transaction, you can use the IUnitOfWork interface to perform database operations within a transaction. Here's an example of how to use transactions in a request handler:

  1. IUnitOfWorkFactory is used to create a unit of work for a specific entity type.
  2. The IUnitOfWork interface provides methods for creating repositories for different entity types, allowing you to perform operations on multiple entities within the same transaction.
  3. The StartAsync method is called to begin the transaction.
  4. The CommitAsync method is called to commit the transaction after all operations are completed successfully.
  5. If any operation fails, the transaction will be rolled back automatically when the unit of work is disposed.
  6. You can also manually roll back the transaction using the RollbackAsync method.
using Microservice.Api;
using Microservice.Data;
using Microservice.Models;

class MyRequestHandler(IUnitOfWorkFactory unitOfWorkFactory) : IRequestHandler
{
	public async Task<Guid> AddAsync(MyFormModel request, CancellationToken cancellationToken)
	{
		await using var unitOfWork = unitOfWorkFactory.Create<MyEntity>();
		await unitOfWork.StartAsync(ct: cancellationToken);
        var myRepos = unitOfWork.GetRepository<MyEntity, Guid>();
        var logRepos = unitOfWork.GetRepository<LogEntity, Guid>();
		var id = await myRepos.AddAsync<MyModel>(request, cancellationToken: cancellationToken);
		await logRepos.AddAsync(new LogEntity { Message = $"Added entity with ID: {id}" }, cancellationToken: cancellationToken);
		await unitOfWork.CommitAsync(cancellationToken);
		return id;
	}
}

Notice: IUnitOfWorkFactory.Create<T>() parameter T must be an entity class that is decorated with the [Database] attribute, which specifies the database provider and connection name. The IUnitOfWork instance created by the factory will manage the transaction for that specific entity type and its associated database connection.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  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. 
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.0.23 43 10/29/2026
1.0.22 48 10/29/2026
1.0.21 54 10/27/2026
1.0.20 46 10/27/2026
1.0.19 50 10/27/2026
1.0.18 51 10/27/2026
1.0.17 83 10/25/2026
1.0.16 97 10/24/2026
1.0.15 95 10/23/2026
1.0.14 96 10/19/2026
1.0.13 92 10/15/2026
1.0.12 86 10/14/2026
1.0.11 98 10/13/2026
1.0.10 81 10/13/2026
1.0.9 86 10/12/2026
1.0.8 87 10/12/2026
1.0.6 91 10/7/2026
1.0.5 129 10/7/2026
1.0.4 102 10/6/2026
1.0.3 102 10/2/2026
Loading failed