# About

Learn to use Eiffel framework to create modern API's that are sustainable, robust, efficient and cloud based.

Introducing our cutting-edge .Net framework, designed to empower you in building reliable, sustainable, robust, and efficient applications. Our platform offers a seamless development experience, enabling you to commence your projects with a monolith application, while also providing a hassle-free migration path to a microservices architecture in just a matter of days.&#x20;

This unique flexibility allows you to adapt and evolve your solutions as your needs grow, ensuring scalability and agility. With our framework, you can unleash your creativity and deliver high-performance applications that meet the demands of today's dynamic digital landscape. Embrace the future of application development with our innovative .Net framework and unlock your full potential.

{% hint style="info" %}
**Good to know:** Ensure a solid understanding of domain-driven design fundamentals as a prerequisite for utilizing our .Net framework. Knowledge of these principles will enable you to build reliable, scalable, and business-aligned applications that maximize the framework's potential and deliver sustainable solutions.
{% endhint %}


# Cross cutting concerns


# API response consistency

The `ApiResponseFilter` is an action filter attribute that provides consistent structure to API responses. It wraps the API response body within an `ApiResponse` class.

```csharp
/// <summary>
/// Api response
/// </summary>
public class ApiResponse
{
    /// <summary>
    /// Error messages
    /// </summary>
    public string[]? Errors { get; init; }

    /// <summary>
    /// Success flag
    /// </summary>
    public bool IsSuccess { get; init; }

    /// <summary>
    /// Response body
    /// </summary>
    public object? Data { get; init; }

    /// <summary>
    /// Status code
    /// </summary>
    public HttpStatusCode StatusCode { get; init; }
}
```

#### Model Validation

If the model state is invalid, the filter captures the errors and returns a structured error response with an HTTP status code of `400 Bad Request`.

#### Installation

```bash
dotnet add package Eiffel.CrossCutting.ApiResponseConsistency
```

You should install **Eiffel.CrossCutting.ApiResponseConsistency** NuGet package into your application.&#x20;

#### Usage

To apply this filter, decorate your controllers or actions with `[ApiResponseFilter]`.

{% hint style="info" %}
For better experience decorate your metho&#x64;**`ProducesDefaultResponseType`**&#x61;nd **`ProducesResponseType`**&#x62;y using **ApiResponse** and **ApiResponse\<T>** classes.
{% endhint %}

```csharp
[ApiResponseFilter]
public class BookingController : ControllerBase
{
    [HttpPost]
    [ProducesDefaultResponseType(typeof(ApiResponse))]
    [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ApiResponse<CreateBookingResponse>))]
    public async Task<CreateBookingResponse> PostAsync([FromBody] CreateBookingRequest request)
    {
        // Your implementation details..
    }
}
```

To appy this filter to all controllers in your application, add to Mvc filters.

```csharp
// Program.cs (.NET5 and above)
public static async Task Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    
    // Applies api response filter for all controllers
    builder.Services.AddControllers(options =>
    {
        options.Filters.Add<ApiResponseFilter>();
    });
     
    var app = builder.Build();
    app.Run();
}
```

**Disabling consistency for specific actions/controllers**

If you don't want a particular action or controller to be wrapped with this consistency logic, decorate it with the `DisableApiResponseConsistency` attribute.

```csharp
[DisableApiResponseConsistency]
public class FileController : ControllerBase
{
    [HttpPost]
    public async Task PostAsync(IFormFile file)
    {
        // Your implementation details..
    }
}
```


# Global exception handling

The `GlobalExceptionFilter` is an attribute designed to handle exceptions globally across your application. By using this filter, you can centralize the logic for handling exceptions, making it easier to manage and maintain.

#### Key Features

*Exception handling*: Handles exceptions both synchronously and asynchronously.

*Service integration*: Integrates with an optional `IExceptionHandler` service, if available, to delegate the exception handling process. Thus you can build your own exception handling mechanism.

*HTTP response mapping*: Maps exceptions to their respective HTTP status codes and produces a consistent API response. Specifically for **HttpRequestException** class.

#### Installation

```bash
dotnet add package Eiffel.CrossCutting.ExceptionHandling
```

You should install **Eiffel.CrossCutting.ExceptionHandling** NuGet package into your application.&#x20;

#### Usage

To appy this filter to all controllers in your application, add to Mvc filters.

```csharp
// Program.cs (.NET5 and above)
public static async Task Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    
    // Applies api response filter for all controllers
    builder.Services.AddControllers(options =>
    {
        options.Filters.Add<GlobalExceptionFilter>();
    });
     
    var app = builder.Build();
    app.Run();
}
```

#### Custom exception handling&#x20;

The `IExceptionHandler` interface provides a contract for handling exceptions. By implementing this interface, you can provide custom logic to determine the HTTP status code and error message based on different exceptions.

```csharp
/// <summary>
/// Exception handler
/// </summary>
public interface IExceptionHandler
{
    /// <summary>
    /// Handle synchronously operation exceptions 
    /// </summary>
    /// <param name="exception">Exception</param>
    /// <returns>HttpStatusCode, ErrorMessage tuple</returns>
    Tuple<HttpStatusCode, string> Handle(Exception exception);

    /// <summary>
    /// Handle asynchronously operation exceptions
    /// </summary>
    /// <param name="exception">Exception</param>
    /// <returns>HttpStatusCode, ErrorMessage tuple</returns>
    Task<Tuple<HttpStatusCode, string>> HandleAsync(Exception exception);
}
```

Example exception handler

```csharp
public class CustomExceptionHandler : IExceptionHandler
{
    public Tuple<HttpStatusCode, string> Handle(Exception exception) 
    {
        // Your implementation details.. (logging, localization etc.)
        
        // Return HTTP status code and error message
        return new Tuple<HttpStatusCode, string>(statusCode, errorMessage);
    }
    
    public async Task<Tuple<HttpStatusCode, string>> HandleAsync(Exception exception)
    {
        // Your implementation details.. (logging, localization etc.)
        
        // Return HTTP status code and error message
        return new Tuple<HttpStatusCode, string>(statusCode, errorMessage);
    }
}
```

After implementation you should register exception handler class.

```csharp
// Program.cs (.NET5 and above)
public static async Task Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    
    // Register your custom exception handler
    builder.Services.AddSingleton<IExceptionHandler, CustomExceptionHandler>();
     
    var app = builder.Build();
    app.Run();
}
```


# Idempotency

IdempotentRequest Action Filter Attribute

The `IdempotentRequest` attribute is designed to ensure that a certain action is executed only once, regardless of the number of requests received. This is particularly useful for preventing duplicate processing in situations where the client might send the same request multiple times, intentionally or unintentionally.

#### Installation

You should install **Eiffel.CrossCutting.Idempotency** NuGet package into your application.&#x20;

```sh
dotnet add package Eiffel.CrossCutting.Idempotency
```

This feature requires distributed caching, pelase visit [Caching](/features/caching) module.

#### Usage

To use this attribute, simply annotate the desired action method in your controller with

```csharp
[IdempotentRequest]
public async Task PostAsync([FromBody] CreateBookingRequest request)
{
  .. // Your implementation details
}
```

#### Options

```csharp
/// <summary>
/// Idempotency options
/// </summary>
public class IdempotencyOptions
{
    /// <summary>
    /// Header key identifier
    /// </summary>
    public string HeaderKeyIdentifier { get; set; } = "x-idempotency-key";

    /// <summary>
    /// Expire time
    /// </summary>
    public int ExpireTimeInSeconds { get; set; } = 0;

    /// <summary>
    /// Cache key prefix
    /// </summary>
    public string CacheKeyPrefix { get; set; } = "idempotency:{0}";

    /// <summary>
    /// Cache db index
    /// </summary>
    public int CacheDbIndex { get; set; } = 0;
}
```

The `IdempotencyOptions` class provides configurable options for the idempotency module. These options allow you to specify the behavior of idempotency checks in the system.\
\
*HeaderKeyIdentifier***:** Specifies the name of the HTTP header used to uniquely identify a request for idempotency checks.\
\
*ExpireTimeInSeconds***:** Sets the duration for which an idempotency record is retained in the cache. After this duration, the record is automatically removed, allowing a request with the same idempotency key to be processed again. The time is expressed in seconds. A value of `0` indicates that the records do not expire automatically.\
\
*CacheKeyPrefix***:** Defines the format of the cache keys used to store idempotency records. The `{0}` placeholder is replaced with the actual idempotency key from the request.\
\
*CacheDbIndex***:** Specifies the database index used when storing idempotency records in a Redis cache (or similar distributed cache that supports multiple databases). This allows you to separate idempotency records from other data in your cache.<br>

**Configuration**\
This class is typically used in the Startup configuration method where it is registered with the dependency injection system and its properties are set based on configuration file values or hardcoded settings. After being registered, the options are used by the idempotency middleware or action filter to determine the behavior of idempotency checks.

{% hint style="info" %}
The `IdempotencyOptions` configuration is optional; if not specified, the system will use the default values.
{% endhint %}

```csharp
// Program.cs (.NET5 and above)
public static async Task Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.Configure<IdempotencyOptions>(options =>
    {
        options.HeaderKeyIdentifier = "X-Request-Id";
        options.ExpireTimeInSeconds = 3600;
        options.CacheKeyPrefix = "customPrefix:{0}";
        options.CacheDbIndex = 1;
    });
 
    var app = builder.Build();
    app.Run();
}
```


# Audit logging


# Caching

The `ICacheService` interface defines a standard set of operations for caching mechanisms. It provides methods for asynchronous and synchronous retrieval and storage of cache items, allowing for both timespan-based and datetime-offset-based expiration. \
\
Additionally, it offers a mechanism to verify the existence of a specific cache key. Implement this interface to create consistent caching providers for different storage backends.

```csharp
/// <summary>
/// Common cache provider interface
/// </summary>
public interface ICacheService
{
    /// <summary>
    /// Gets cache value
    /// </summary>
    /// <typeparam name="T">The type of result object</typeparam>
    /// <param name="cacheKey">Cache key</param>
    /// <returns>Object</returns>
    T Get<T>(string cacheKey);
    
    /// <summary>
    /// Gets cache value asynchronous
    /// </summary>
    /// <typeparam name="T">The type of result object</typeparam>
    /// <param name="cacheKey">Cache key</param>
    /// <returns>Object</returns>
    Task<T> GetAsync<T>(string cacheKey);
    
    /// <summary>
    /// Sets cache value asynchronous
    /// </summary>
    /// <typeparam name="T">The type of source object</typeparam>
    /// <param name="cacheKey">Cache key</param>
    /// <param name="value">Object value</param>
    /// <param name="expiresIn">Expires after given value</param>
    void Set<T>(string cacheKey, T value, TimeSpan? expiresIn = null);
    
    /// <summary>
    /// Sets cache value asynchronous
    /// </summary>
    /// <typeparam name="T">The type of source object</typeparam>
    /// <param name="cacheKey">Cache key</param>
    /// <param name="value">Object value</param>
    /// <param name="expiresIn">Expires after given value</param>
    Task SetAsync<T>(string cacheKey, T value, TimeSpan? expiresIn = null);
    
    /// <summary>
    /// Sets cache value synchronous
    /// </summary>
    /// <typeparam name="T">The type of source object</typeparam>
    /// <param name="cacheKey">Cache key</param>
    /// <param name="value">Object value</param>
    /// <param name="expiresOn">Expires on given date time offset</param>
    void Set<T>(string cacheKey, T value, DateTimeOffset expiresOn);
    
    /// <summary>
    /// Sets cache value asynchronous
    /// </summary>
    /// <typeparam name="T">The type of source object</typeparam>
    /// <param name="cacheKey">Cache key</param>
    /// <param name="value">Object value</param>
    /// <param name="expiresOn">Expires on given date time offset</param>
    Task SetAsync<T>(string cacheKey, T value, DateTimeOffset expiresOn);
    
    /// <summary>
    /// Removes cache key
    /// </summary>
    /// <param name="cacheKey">Cache key</param>
    void Delete(string cacheKey);
    
    /// <summary>
    /// Removes cache key
    /// </summary>
    /// <param name="cacheKey">Cache key</param>
    Task DeleteAsync(string cacheKey);

    /// <summary>
    /// Checks given key is exist in cache or not
    /// </summary>
    /// <param name="cacheKey">Cache key</param>
    /// <returns>true/false</returns>
    bool IsExists(string cacheKey);
}
```


# Configuration

Caching module requires serveral NuGet package installations. First you need to install **Eiffel.Caching.Extensions.DependencyInjection** package.

```sh
dotnet add package Eiffel.Caching.Extensions.DependencyInjection
```

{% hint style="info" %}
After the installation, **AddCaching** extension method will be accessible from `WebApplicationBuilder` class instance.
{% endhint %}

The Caching module provides distributed and in-memory caching options. The [`CacheSource`](/features/caching/api/cachesource) enum provides a list of supported cache sources

You can use the AddCaching method *without parameters*, but in that case, you must define the Caching section with the related source configuration in the appsettings.json file.

```csharp
// Program.cs (.NET5 and above)
public static async Task Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    
    // Add caching
    builder.AddCaching();
     
    var app = builder.Build();
    app.Run();
}
```

Example **Redis** configuration section. For configuration details please [read](/features/caching/configuration/redis).

```json
{
    "Caching": {
        "Source": "Redis",
        "Redis": {
            ... // Put your redis configuration values here
        }
    }
}
```

Example **In-Memory** configuration section. For configuration details please [read](/features/caching/configuration/in-memory).

```json
{
    "Caching": {
        "Source": "InMemory",
        "InMemory": {
            ... // Put your in-memory configuration values here
        }
    }
}
```


# In-Memory

In-Memory cache provides own configuration properties. For configuration details please [visit](/features/caching/api/inmemorycacheoptions).

You can configure values from appsettings.json file

```json
{
    "Caching": {
        "Source": "InMemory",
        "InMemory": {
           "TrackStatistics": true,
           "ExpirationScanFrequencyInSeconds" : 30
        }
    }
}
```

If you need to advanced configuration or configure cache service without appsettings.json file. You can use extension method.

AddCaching method initally read values from appsettings.json file afterwards applies configuration from action method.

```csharp
// Program.cs (.NET5 and above)
public static async Task Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    
    // Add with configuration instance
    var cacheOptions = new InMemoryCacheOptions();
    cacheOptions.ExpirationScanFrequencyInSeconds = 30;
    cacheOptions.Clock = new CustomSystemClock(); // Your custom ISystemClock implementation.
    builder.AddCaching(x => x.InMemory(cacheOptions));

    // Add with inline action method
    builder.AddCaching(x => x.InMemory(x => x.ExpirationScanFrequencyInSeconds = 120));
 
    var app = builder.Build();
    app.Run();
}
```


# Redis

Redis cache provides own configuration properties. For configuration details please [visit](/features/caching/api/rediscacheoptions).

You can configure values from appsettings.json file

```json
{
    "Caching": {
        "Source": "Redis",
        "Redis": {
            "Hosts": [
                "localhost:6379",
            ],
            "Username": "admin",
            "Password": "your+str0ng_Password!"
        }
    }
}
```

If you need to advanced configuration or configure cache service without appsettings.json file. You can use extension method.\
\
AddCaching method initally read values from appsettings.json file afterwards applies configuration from action method.

```csharp
// Program.cs (.NET5 and above)
public static async Task Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    
    // Add with configuration instance
    var cacheOptions = new RedisCacheOptions();
    cacheOptions.Hosts = new [] { "localhost:6379" };
    cacheOptions.UserName = "admin";
    cacheOptions.Password = "your+str0ng_Password!";
    builder.AddCaching(x => x.Redis(cacheOptions));

    // Add with inline action method
    builder.AddCaching(x => x.Redis(x => x.BacklogPolicy = StackExchange.Redis.BacklogPolicy.FailFast));
 
    var app = builder.Build();
    app.Run();
}
```


# Usage

{% hint style="info" %}
Before continue with this section please follow [configuration](/features/caching/configuration) steps.
{% endhint %}

After the configuration, you should install **Eiffel.Caching.Abstractions** NuGet package into your application. This package contains common interfaces such as [`ICacheService`](/features/caching/api/icacheservice), [`ICacheServiceFactory`](/features/caching/api/icacheservicefactory) etc.

```sh
dotnet add package Eiffel.Caching.Abstractions
```

In your application services, controllers or other infrastructure service you can use `ICacheService` with dependency injection.&#x20;

```csharp
public class BookingService
{
    private readonly ICacheService _cacheService;
    public BookingService(ICacheService cacheService)
    {
        _cacheService = cacheService;
    }
    
    .. // Your implementation details
}
```

If you want to separate your data between different indexes in Redis you can use `ICacheServiceFactory`

```csharp
public class BookingService
{
    const int BookingCacheIndex = 10;
    
    private readonly ICacheService _cacheService;
    public BookingService(ICacheServiceFactory cacheServiceFactory)
    {
        _cacheService = cacheServiceFactory.Resolve(BookingCacheIndex);
    }
    
    .. // Your implementation details 
}
```


# API


# CacheSource

CacheSource enum provides a list of supported cache sources

```csharp
/// <summary>
/// Cache sources
/// </summary>
public enum CacheSource
{
    /// <summary>
    /// Default
    /// </summary>
    None = 0,
    
    /// <summary>
    /// In-Memory caching
    /// </summary>
    InMemory = 1,
    
    /// <summary>
    /// Redis
    /// </summary>
    Redis = 2
}
```


# InMemoryCacheOptions

In-Memory cache options

```csharp
/// <summary>
/// In-Memory cache options
/// </summary>
public class InMemoryCacheOptions
{
    /// <summary>
    /// Sets system clock
    /// </summary>
    public ISystemClock Clock { get; set; }

    /// <summary>
    /// Gets or sets the minimum length of time between successive scans for expired items.
    /// Default value is 60 seconds
    /// </summary>
    public int ExpirationScanFrequencyInSeconds{ get; set; } = 60;

    /// <summary>
    /// Gets or sets the maximum size of the cache.
    /// Default value is null.
    /// </summary>
    public ulong? SizeLimit { get; set; }

    /// <summary>
    /// Gets or sets the amount to compact the cache by when the maximum size is exceeded.
    /// Value must be between 0 and 1.
    /// Default value is 0.05
    /// </summary>
    public double CompactionPercentage { get; set; }

    /// <summary>
    /// Gets or sets whether to track memory cache statistics.
    /// Disabled by default (false).
    /// </summary>
    public bool TrackStatistics { get; set; }

    /// <summary>
    /// Gets or sets whether to track linked entries.
    /// Disabled by default (false).
    /// </summary>
    /// <remarks>Prior to .NET 7 this feature was always enabled.</remarks>
    public bool TrackLinkedCacheEntries { get; set; }
}
```


# RedisCacheOptions

Redis cache options

<pre class="language-csharp" data-full-width="false"><code class="lang-csharp"><strong>/// &#x3C;summary>
</strong>/// Redis cache options
/// &#x3C;/summary>
public class RedisCacheOptions  
{
    /// &#x3C;summary>
    /// Gets or sets whether connect/configuration timeouts should be explicitly notified via a TimeoutException.
    /// Default value is true
    /// &#x3C;/summary>
    public bool AbortOnConnectFail { get; set; } 

    /// &#x3C;summary>
    /// Indicates whether admin operations should be allowed.
    /// Default value is false
    /// &#x3C;/summary>
    public bool AllowAdmin { get; set; } 

    /// &#x3C;summary>
    /// Specifies the time in milliseconds that the system should allow for asynchronous operations (defaults to SyncTimeout).
    /// &#x3C;/summary>
    public int AsyncTimeout { get; set; } 

    /// &#x3C;summary>
    /// Gets or sets whether the library should identify itself by library-name/version when possible.
    /// Default value is true
    /// &#x3C;/summary>
    public bool SetClientLibrary { get; set; } 
    
    /// &#x3C;summary>
    /// Gets or sets the library name to use for CLIENT SETINFO lib-name calls to Redis during handshake.
    /// Defaults value is "SE.Redis".
    /// &#x3C;/summary>
    /// &#x3C;remarks>If the value is null, empty or whitespace, then the value from the options-provideer is used;
    /// to disable the library name feature, use &#x3C;see cref="SetClientLibrary"/> instead.&#x3C;/remarks>
    public string? LibraryName { get; set; } 

    /// &#x3C;summary>
    /// Automatically encodes and decodes channels.
    /// &#x3C;/summary>
    public RedisChannel ChannelPrefix { get; set; } 
    
    /// &#x3C;summary>
    /// The client name to use for all connections.
    /// &#x3C;/summary>
    public string? ClientName { get; set; } 
    
    /// &#x3C;summary>
    /// Channel to use for broadcasting and listening for configuration change notification.
    /// Default value is "__Booksleeve_MasterChanged"
    /// &#x3C;/summary>
    public string? ConfigurationChannel { get; set; } 

    /// &#x3C;summary>
    /// Check configuration every n seconds (every minute by default).
    /// &#x3C;/summary>
    public int ConfigCheckSeconds { get; set; } 

    /// &#x3C;summary>
    /// Specifies the time in milliseconds that should be allowed for connection (defaults to 5 seconds unless SyncTimeout is higher).
    /// &#x3C;/summary>
    public int ConnectTimeoutInMilliseconds { get; set; } 

    /// &#x3C;summary>
    /// Specifies the default database to be used when calling &#x3C;see cref="ConnectionMultiplexer.GetDatabase(int, object)"/> without any parameters.
    /// &#x3C;/summary>
    public int? DefaultDatabase { get; set; } 

    /// &#x3C;summary>
    /// Specifies the time in seconds at which connections should be pinged to ensure validity.
    /// -1 Defaults to 60 Seconds
    /// &#x3C;/summary>
    public int KeepAliveInSeconds { get; set; } 

    /// &#x3C;summary>
    /// The username to use to authenticate with the server.
    /// &#x3C;/summary>
    public string? UserName { get; set; } 

    /// &#x3C;summary>
    /// The password to use to authenticate with the server.
    /// &#x3C;/summary>
    public string? Password { get; set; } 

    /// &#x3C;summary>
    /// Type of proxy to use (if any); for example &#x3C;see cref="StackExchange.Redis.Proxy"/>.
    /// Default value is Proxy.None
    /// &#x3C;/summary>
    public Proxy Proxy { get; set; } 

    /// &#x3C;summary>
    /// The backlog policy to be used for commands when a connection is unhealthy.
    /// &#x3C;/summary>
    public BacklogPolicy? BacklogPolicy { get; set; } 

    /// &#x3C;summary>
    /// Indicates whether endpoints should be resolved via DNS before connecting.
    /// If enabled the ConnectionMultiplexer will not re-resolve DNS when attempting to re-connect after a connection failure.
    /// Default value is false
    /// &#x3C;/summary>
    public bool ResolveDns { get; set; } 

    /// &#x3C;summary>
    /// The service name used to resolve a service via sentinel.
    /// &#x3C;/summary>
    public string? ServiceName { get; set; } 

    /// &#x3C;summary>
    /// Indicates whether the connection should be encrypted.
    /// &#x3C;/summary>
    public bool Ssl { get; set; } 

    /// &#x3C;summary>
    /// Gets or sets the SocketManager instance to be used with these options.
    /// If this is null a shared cross-multiplexer &#x3C;see cref="SocketManager"/> is used.
    /// &#x3C;/summary>
    /// &#x3C;remarks>
    /// This is only used when a &#x3C;see cref="ConnectionMultiplexer"/> is created.
    /// Modifying it afterwards will have no effect on already-created multiplexers.
    /// &#x3C;/remarks>
    public SocketManager? SocketManager { get; set; } 

    /// &#x3C;summary>
    /// A &#x3C;see cref="SslClientAuthenticationOptions"/> provider for a given host, for custom TLS connection options.
    /// Note: this overrides *all* other TLS and certificate settings, only for advanced use cases.
    /// &#x3C;/summary>
    public Func&#x3C;string, SslClientAuthenticationOptions>? SslClientAuthenticationOptions { get; set; } 

    /// &#x3C;summary>
    /// The target-host to use when validating SSL certificate; setting a value here enables SSL mode.
    /// &#x3C;/summary>
    public string? SslHost { get; set; } 

    /// &#x3C;summary>
    /// Configures which SSL/TLS protocols should be allowed.  If not set, defaults are chosen by the .NET framework.
    /// &#x3C;/summary>
    public SslProtocols SslProtocols { get; set; } 

    /// &#x3C;summary>
    /// Specifies the time in milliseconds that the system should allow for synchronous operations (defaults to 5 seconds).
    /// &#x3C;/summary>
    public int SyncTimeoutInSeconds { get; set; } 

    /// &#x3C;summary>
    /// Tie-breaker used to choose between primaries (must match the endpoint exactly).
    /// &#x3C;/summary>
    public string? TieBreaker { get; set; } 

    /// &#x3C;summary>
    /// The server version to assume.
    /// Default version is RedisFeatures.v3_0_0 &#x3C;see cref="RedisFeatures"/>
    /// &#x3C;/summary>
    public Version? Version { get; set; } 

    /// &#x3C;summary>
    /// A Boolean value that specifies whether the certificate revocation list is checked during authentication.
    /// &#x3C;/summary>
    public bool CheckCertificateRevocation { get; set; } 

    /// &#x3C;summary>
    /// Redis host:port endpoints
    /// &#x3C;/summary>
    public string[]? Hosts { get; set; } 

    /// &#x3C;summary>
    /// Controls how often the connection heartbeats. A heartbeat includes:
    /// - Evaluating if any messages have timed out
    /// - Evaluating connection status (checking for failures)
    /// - Sending a server message to keep the connection alive if needed
    /// &#x3C;/summary>
    /// &#x3C;remarks>
    /// This defaults to 1000 milliseconds and should not be changed for most use cases.
    /// If for example you want to evaluate whether commands have violated the &#x3C;see cref="RedisCacheOptions.AsyncTimeout"/> at a lower fidelity
    /// than 1000 milliseconds, you could lower this value.
    /// Be aware setting this very low incurs additional overhead of evaluating the above more often.
    /// &#x3C;/remarks>
    public TimeSpan HeartbeatInterval { get; set; } 

    /// &#x3C;summary>
    /// Reconnect retry policy
    /// &#x3C;/summary>
    public IReconnectRetryPolicy? ReconnectRetryPolicy { get; set; } 

    /// &#x3C;summary>
    /// Should exceptions include identifiable details? (key names, additional .Data annotations)
    /// Default value is true
    /// &#x3C;/summary>
    public bool IncludeDetailInExceptions { get; set; } 

    /// &#x3C;summary>
    /// Should exceptions include performance counter details?
    /// &#x3C;/summary>
    /// &#x3C;remarks>
    /// CPU usage, etc - note that this can be problematic on some platforms.
    /// Default value is false
    /// &#x3C;/remarks>
    public bool IncludePerformanceCountersInExceptions { get; set; } 

    /// &#x3C;summary>
    /// The number of times to repeat the initial connect cycle if no servers respond promptly.
    /// Default value is 3
    /// &#x3C;/summary>
    public int ConnectRetry { get; set; } 

    /// &#x3C;summary>
    /// Allows custom transport implementations, such as http-tunneling via a proxy.
    /// &#x3C;/summary>
    public Tunnel? Tunnel { get; set; } 

    /// &#x3C;summary>
    /// Allows modification of a &#x3C;see cref="Socket"/> between creation and connection.
    /// Passed in is the endpoint we're connecting to, which type of connection it is, and the socket itself.
    /// For example, a specific local IP endpoint could be bound, linger time altered, etc.
    /// &#x3C;/summary>
    public Action&#x3C;EndPoint, ConnectionType, Socket>? BeforeSocketConnect { get; set; } 

    /// &#x3C;summary>
    /// A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication; note
    /// that this cannot be specified in the configuration-string.
    /// &#x3C;/summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")]
    public event LocalCertificateSelectionCallback? CertificateSelection;

    /// &#x3C;summary>
    /// A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party; note
    /// that this cannot be specified in the configuration-string.
    /// &#x3C;/summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")]
    public event RemoteCertificateValidationCallback? CertificateValidation;
}

</code></pre>


# ICacheService

```csharp
/// <summary>
/// Common cache provider interface
/// </summary>
public interface ICacheService
{
    /// <summary>
    /// Gets cache value
    /// </summary>
    /// <typeparam name="T">The type of result object</typeparam>
    /// <param name="cacheKey">Cache key</param>
    /// <returns>Object</returns>
    T Get<T>(string cacheKey);
    
    /// <summary>
    /// Gets cache value asynchronous
    /// </summary>
    /// <typeparam name="T">The type of result object</typeparam>
    /// <param name="cacheKey">Cache key</param>
    /// <returns>Object</returns>
    Task<T> GetAsync<T>(string cacheKey);
    
    /// <summary>
    /// Sets cache value asynchronous
    /// </summary>
    /// <typeparam name="T">The type of source object</typeparam>
    /// <param name="cacheKey">Cache key</param>
    /// <param name="value">Object value</param>
    /// <param name="expiresIn">Expires after given value</param>
    void Set<T>(string cacheKey, T value, TimeSpan? expiresIn = null);
    
    /// <summary>
    /// Sets cache value asynchronous
    /// </summary>
    /// <typeparam name="T">The type of source object</typeparam>
    /// <param name="cacheKey">Cache key</param>
    /// <param name="value">Object value</param>
    /// <param name="expiresIn">Expires after given value</param>
    Task SetAsync<T>(string cacheKey, T value, TimeSpan? expiresIn = null);
    
    /// <summary>
    /// Sets cache value synchronous
    /// </summary>
    /// <typeparam name="T">The type of source object</typeparam>
    /// <param name="cacheKey">Cache key</param>
    /// <param name="value">Object value</param>
    /// <param name="expiresOn">Expires on given date time offset</param>
    void Set<T>(string cacheKey, T value, DateTimeOffset expiresOn);
    
    /// <summary>
    /// Sets cache value asynchronous
    /// </summary>
    /// <typeparam name="T">The type of source object</typeparam>
    /// <param name="cacheKey">Cache key</param>
    /// <param name="value">Object value</param>
    /// <param name="expiresOn">Expires on given date time offset</param>
    Task SetAsync<T>(string cacheKey, T value, DateTimeOffset expiresOn);
    
    /// <summary>
    /// Removes cache key
    /// </summary>
    /// <param name="cacheKey">Cache key</param>
    void Delete(string cacheKey);
    
    /// <summary>
    /// Removes cache key
    /// </summary>
    /// <param name="cacheKey">Cache key</param>
    Task DeleteAsync(string cacheKey);
    
    /// <summary>
    /// Checks given key is exist in cache or not
    /// </summary>
    /// <param name="cacheKey">Cache key</param>
    /// <returns>true/false</returns>
    bool IsExists(string cacheKey);
}
```


# ICacheServiceFactory

Cache factory resolves cache service with given index. You can use this method for both cache source but only useful when used with Redis.

```csharp
/// <summary>
/// Cache service factory
/// </summary>
public interface ICacheServiceFactory
{
    /// <summary>
    /// Resolves cache service
    /// </summary>
    /// <param name="dbIndex">Cache index</param>
    ICacheService Resolve(int dbIndex = 0);
}
```


# Localization


# Job Processing

Distributed, scalable, loosely coupled job processing


# Multi-Tenancy


# Metrics & monitoring


# Transactional outbox


# PostgreSQL


# MongoDB (cluster only)


# Messaging


# Kafka


# Rabbit MQ


# Azure Service Bus


# Awaitable socket client


# Graceful shutdown


# Persistence

Repository base class and other requirements.

#### Motivation

> A *repository* represents all objects of a certain type as a conceptual set (usually emulated). **It acts like a collection**, except with more elaborate querying capability. \[...] For each type of object that needs global access, **create an object that can provide the illusion of an in-memory collection** of all objects of that type.\
> \
> ***Eric Evans - Domain Driven Design***

Most repository patterns contain many query methods, and they are often nearly identical to the DbContext class. Unlike the norm, the Eiffel framework follows a collection-oriented repository approach."

Each repository should expose a single aggregate, and the maintenance of the entities or value objects should be handled by the owner aggregate.<br>

```csharp
/// <summary>
/// IRepository interface
/// </summary>
/// <typeparam name="TAggregate">The type of aggregate</typeparam>
/// <typeparam name="TIdentity">The tpye of aggregate identity</typeparam>
/// <typeparam name="TKey">The type of database primary key</typeparam>
public interface IRepository<TAggregate, TIdentity, TKey>
    where TKey : struct, IEquatable<TKey>
    where TIdentity : class
    where TAggregate : Aggregate<TIdentity, TKey>
{
    /// <summary>
    /// Gets record from database
    /// </summary>
    /// <param name="identity">Aggregate</param>
    /// <param name="cancellationToken">Cancellation token</param>
    Task<TAggregate> GetAsync(TIdentity identity, CancellationToken cancellationToken = default);

    /// <summary>
    /// Adds record to database
    /// </summary>
    /// <param name="aggregate">Aggregate identifier</param>
    /// <param name="cancellationToken">Cancellation token</param>
    /// <returns>Record from database</returns>
    Task AddAsync(TAggregate aggregate, CancellationToken cancellationToken = default);


    /// <summary>
    /// Commit changes to database
    /// </summary>
    /// <param name="aggregate">Aggregate</param>
    /// <param name="cancellationToken">Cancellation token</param>
    Task SaveChangesAsync(TAggregate aggregate, CancellationToken cancellationToken = default);
}
```


# Modelling


# Domain-Driven Design

## How Projects work

Nullam quis risus eget urna mollis ornare vel eu leo. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Maecenas sed diam eget risus varius blandit sit amet non magna. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec id elit non mi porta gravida at eget metus. Donec id elit non mi porta gravida at eget metus.

### The Basics

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.

Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.

### Creating a Project

Nullam quis risus eget urna mollis ornare vel eu leo. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

### Organizing your Projects

Sed posuere consectetur est at lobortis. Curabitur blandit tempus porttitor. Donec ullamcorper nulla non metus auctor fringilla. Donec sed odio dui.

Curabitur blandit tempus porttitor. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.


# Aggregates

An Aggregate is a cluster of domain objects that are treated as a single unit with regards to data changes.

The aggregate ensures that all the changes to the objects within the aggregate are performed in a consistent and transactional manner.<br>

Key characteristics of an Aggregate are:

1. **Consistency Boundary**: The aggregate defines a clear boundary for transactional consistency. All invariants and business rules within an aggregate must be satisfied as a whole, ensuring that the domain remains in a valid state at all times.
2. **Encapsulation**: The internal structure and state of the aggregate's objects are hidden from the outside world. External entities can only interact with the aggregate through its root.
3. **Lifecycle**: Aggregates are typically long-lived, persisting over multiple transactions. They should be designed with consideration for their lifecycle management.
4. **Isolation**: Aggregates should not directly reference or hold references to other aggregates. Instead, they can reference other aggregates by their unique identifiers (IDs).

{% hint style="info" %}
**Eiffel.Modelling.Abstractions** NuGet package contains base aggregate class. By using abstract Aggregate class you can define your aggregates.
{% endhint %}

```csharp
/// <summary>
/// Aggregate implementation
/// </summary>
/// <typeparam name="TIdentity">The type of unique business identifier</typeparam>
/// <typeparam name="TKey">The type of database primary key</typeparam>
public abstract class Aggregate<TIdentity, TKey> : EntityBase<TKey>, IAggregate
   where TIdentity : ValueObject<TIdentity>
   where TKey : struct, IEquatable<TKey>
{
    /// <summary>
    /// Domain events collection
    /// </summary>
    public IReadOnlyCollection<IDomainEvent> DomainEvents => _domainEvents.ToList();
    
    /// <summary>
    /// Business identifier
    /// </summary>
    public abstract TIdentity Identity { get; internal set; }
    
    private readonly List<IDomainEvent> _domainEvents;
    /// <summary>
    /// CTOR
    /// </summary>
    public Aggregate()
    {
        _domainEvents = new List<IDomainEvent>();
    }
    
    /// <summary>
    /// Raises/adds domain event
    /// </summary>
    /// <typeparam name="TEvent">The type of the class representing domain event</typeparam>
    /// <param name="domainEvent">Domain event</param>
    protected void Raise<TEvent>(TEvent domainEvent)
        where TEvent : IDomainEvent
    {
        _domainEvents.Add(domainEvent);
    }
    
    /// <summary>
    /// Clears all domain events
    /// </summary>
    public void ClearEvents()
    {
        _domainEvents.Clear();
    }
}
```

Each Aggregate is likely to contain more than one function and these functions are business needs demanded by domain experts/stakeholders. Each function usually requires notifying other members of the system that an event has occurred. These events are called [Domain Events](/principles/domain-driven-design/domain-events). Each Aggregate is responsible for keeping the events occurring within itself.\
\
Each Aggregate must have a uniquely defined identity type and primary key type required for the database. You can find the identity details specific to the aggregates in the [Business Identifiers](/principles/domain-driven-design/business-identifiers) section.\
\
*Example Booking Aggregate with BookingCancelled domain event.*

```csharp
public class Booking : Aggregate<BookingId, Guid>
{
    // Business identifier
    public override BookingId Identifier { get; private set; }

    // Status enum
    public BookingStatus Status { get; private set; }

    // ...
    // ...
    void Cancel(string reason)
    {
        Status = BookingStatus.Cancelled;
        Raise(new BookingCancelled(BookingId, reason));
    }
}
```


# Entities

Entities are uniquely identifiable by a combination of one or more attributes or properties

Entities are distinct from other domain concepts such as Value Objects and Aggregates. Value Objects are immutable objects whose equality is based on their attribute values, while Aggregates are groups of related entities and value objects treated as a single unit for consistency and transactional boundaries.

{% hint style="info" %}
**Eiffel.Modelling.Abstractions** NuGet package contains base Entity class. By using abstract Entity class you can define your entities.
{% endhint %}

```csharp
/// <summary>
/// Base entity class
/// </summary>
/// <typeparam name="TKey">The type of database primary key</typeparam>
public abstract class EntityBase<TKey>
    where TKey : struct, IEquatable<TKey>
{
    /// <summary>
    /// Primary key
    /// </summary>
    [Key]
    public TKey Id { get; internal set; }
}
```

Entities are typically implemented as classes in object-oriented programming languages, and their properties and behavior reflect the essential attributes and operations of the corresponding real-world objects they represent in the domain.

*Example Passenger entity with properties.*

```csharp
public class Passenger : EnttiyBase<long>
{
    public string Name { get; private set; }

    public string Surname { get; private set; }
}
```


# Value Objects

A Value Object represents a conceptually whole value with no identity. It is defined solely by its attributes or properties and is considered immutable, meaning its state cannot be changed after creation. Two Value Objects with the same attributes are considered equal, regardless of their individual identities.<br>

Characteristics of Value Objects:

1. **Immutability**: Once created, the state of a Value Object cannot be modified. Any changes to its properties result in a new Value Object instance.
2. **Equality based on attributes**: Value Objects are compared based on the equality of their attributes rather than their identities.
3. **Side-effect-free**: Value Objects should not have any behavior or actions associated with them. They are primarily used to hold and model data.
4. **Lightweight**: Since Value Objects are immutable and do not have identities, they are typically lightweight and easy to copy.
5. **Replaceable**: If two Value Objects have the same attributes, they can be replaced with each other without any impact on the domain logic.

{% hint style="info" %}
**Eiffel.Modelling.Abstractions** NuGet package contains base ValueObject class. By using abstract ValueObject class you can define your value objects.
{% endhint %}

```csharp
 /// <summary>
 /// Value object
 /// </summary>
 /// <typeparam name="T">The type of value object class</typeparam>
 public abstract class ValueObject<T> where T : ValueObject<T>
 {
     /// <inheritdoc/>
     public override bool Equals(object obj)
     {
         if (obj == null || GetType() != obj.GetType())
             return false;

         T other = (T)obj;
         return GetEqualityComponents().SequenceEqual(other.GetEqualityComponents());
     }

     /// <inheritdoc/>
     public override int GetHashCode()
     {
         return GetEqualityComponents()
             .Aggregate(17, (current, obj) => current * 23 + (obj?.GetHashCode() ?? 0));
     }

     /// <inheritdoc/>
     protected abstract IEnumerable<object> GetEqualityComponents();
 }
```

*Example Location value object.*

```csharp
public class Location : ValueObject<Location>
{
    public string City { get; }

    public string Country { get ;}

    public Location(string city, string country)
    {
        City = city;
        Country = country;
    }
}
```


# Domain Events

Domain Events are an integral part of Domain-Driven Design and are used to communicate changes and trigger side-effects within the domain model.

Domain Events represent real-world events or facts that are relevant to the business or domain. They capture important moments in the lifecycle of domain entities, aggregates, or value objects. By modeling and raising domain events, you can decouple different parts of your domain model and improve the overall maintainability and flexibility of your application.

Key characteristics of Domain Events:

1. **Immutable**: Domain Events are usually immutable objects, meaning their state cannot be modified once created. This ensures that the event represents a specific occurrence at a particular moment.
2. **Side-effects**: Domain Events are often used to trigger side-effects in response to certain actions or state changes. These side-effects can be in the form of notifications, logging, or updates to other parts of the domain model.
3. **Loose coupling**: Raising Domain Events allows you to decouple different parts of the domain model. The entity or aggregate that raises the event doesn't need to know who will handle it, promoting a more flexible and extensible design.
4. **Event-driven** architecture: Domain Events play a significant role in event-driven architectures, where different components or services communicate through events rather than direct method calls.

{% hint style="info" %}
**Eiffel.Modelling.Abstractions** NuGet package contains base IDomainEvent interface. By using IDomainEvent interface you can define your domain events.
{% endhint %}

```csharp
/// <summary>
/// Domain event interface
/// </summary>
public interface IDomainEvent
{
    /// <summary>
    /// Unique event identifier
    /// </summary>
    public Guid Id { get; }
}
```

By using Domain Events, you can ensure that various parts of your application remain loosely coupled, making it easier to understand, extend, and maintain the domain model.\
\
*Example BookingCancelled domain event.*

```csharp
public class BookingCancelled : IDomainEvent
{
    public Guid Id { get; }

    public string BookingId { get; }

    public string CancellationReason { get; }

    public BookingCancelled(BookingId bookingId, string cancellationReason)
    {
        Id = Guid.NewGuid();
        BookingId = bookingId;
        CancellationReason = cancellationReason;
    }
}
```


# Factories


# Domain Services


# Business Identifiers


# Shared Kernel


# Onion Architecture


# Application Layer


# Domain Layer


# Infrastructure Layer


# Anti-Corruption Layer


# Modular Monolith Architecture


# Modules


# Shared Infrastructure


# Microservice Architecture


# API Gateway


# View Model Composition


# Contracts


# Domain Storytelling


# User stories


# Modular Monolith


# Microservices


# Unit Testing


# Integration Testing


# Contract Testing


# CI/CD Pipelines


# Docker


# Kubernates


# Infrastructure as Code


