Calabonga.AspNetCore.AppDefinitions 2.4.3

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

// Install Calabonga.AspNetCore.AppDefinitions as a Cake Tool
#tool nuget:?package=Calabonga.AspNetCore.AppDefinitions&version=2.4.3

Calabonga.AspNetCore.AppDefinitions

Сборка позволяет навести порядок в вашем Program.cs. Можно всё разложить "по полочкам". А еще можно реализовать систему плагинов. Чтобы воспользоваться сборкой надо просто установить nuget-пакет Calabonga.AspNetCore.AppDefinitions.

Что нового

Версия 2.4.3

  • ApplicationOrderIndex сделан virtual для возможности переопределения.

Версия 2.4.2

  • Для ConfgureApplication() и для ConfigureServices() теперь есть свой собственный индекс сортировки.
  • Переработана информация при логировании в ILogger.
  • Исправлены некоторые синтаксические ошибки, а также добавлены новые. 😃

Версия 2.4.1

  • Nuget-пакеты обновлены для использования NET8
  • Был добавлен перехват ошибок при поиске модулей определений (AppDefinition).

Версия 2.4.0

На ряду с версией для NET6.0 добавлена версия для NET8.0. В параметры пакетов добавлены следующие настройки:

  • Source Link
  • Deterministic (dll/exe)
  • Compiler flags

А также исправлены некоторые недочеты в процесс формирования и публикации nuget-пакета.

Версия 2.3.0

Добавлена обработка дубликатов AppDefinitions, которые были найдены в сторонних сборках. Дополнительная информация о найденых дубликатах определений теперь выводиться в процессе отладке (DEBUG) включенном в настройках логирования.

Информация при уровне логирования LogLevel = "Debug":

image5

Информация при уровне логирования LogLevel = "Information":

image5

Версия 2.2.0

Создан шаблон для генерации проекта ASP.NET Web API c AppDefinitions. То есть, чтобы не устанавливать каждый раз Calabonga.AspNetCore.AppDefinitions nuget-пакет в новый (в пустой) проект, можно воспользоваться уже готовым шаблоном, который создаст приложение с установленным nuget-пакетом (плюс еще Serilog). Это гораздо быстрее и удобнее. Я использую этот шаблона в своих видео на своём канале boosty.to/calabonga.

Проект шаблона с инструкцией по использованию.

Версия 2.1.0

  • В новой версии появилась возможность подключения модулей к проекту. Достаточно воспользовать новым способом регистрации.
// Вместо этого (instead of)
builder.AddDefinitions(typeof(Program));

// использовать этот (use this to add definitions for application)
const string moduleFolder = "Modules:Folder";
var modulesPath = builder.Configuration[moduleFolder] ?? throw new ArgumentNullException(moduleFolder);
builder.AddDefinitionsWithModules(modulesPath, typeof(Program));
  • Вывод зарегистрированных AppDefinitions усовершенствована.
[15:43:03 DBG] [AppDefinitions]: From Program
[15:43:03 DBG] [AppDefinitions]: AuthorizationDefinition (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: AuthorizeEndpoints (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: AutomapperDefinition (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: CommonDefinition (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: ContainerDefinition (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: CorsDefinition (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: DataSeedingDefinition (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: DbContextDefinition (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: ErrorHandlingDefinition (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: ETagGeneratorDefinition (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: EventItemEndpoints (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: FluentValidationDefinition (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: MediatorDefinition (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: OpenIddictDefinition (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: ProfilesEndpoints (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: SwaggerDefinition (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: TokenEndpoints (Program) (Enabled: Yes)
[15:43:03 DBG] [AppDefinitions]: UnitOfWorkDefinition (Program) (Enabled: Yes)
[15:43:03 DBG] From Program assemblies totally AppDefinitions found: 18
[15:43:04 DBG] Total AppDefinitions applied: 18
  • Появилась возможность не только включать/выключать определенные AppDefinitions, но и указывать нужно ли их экспортировать или нет. Обратите внимание, что по умолчанию Exported свойство задано как False, то есть, не экспортировать данный AppDefinition. Например, если регистрацию конечной точки (endpoint) WeatherForcast слелать через определение (AppDefinition), то экспорт мог бы выглядеть так:
public class WeatherForecastEndpoints : AppDefinition
{
    /// <summary>
    /// Enables or disables export definition as a content for module that can be exported.
    /// </summary>
    /// /// <remarks>Default values is <c>False</c></remarks>
    public override bool Exported => true;

    public override void ConfigureApplication(WebApplication app)
    {
        app.MapGet("/weatherforecast", WeatherGet)
            .ProducesProblem(401)
            .Produces<WeatherForecast[]>()
            .WithName("GetWeatherForecast")
            .WithTags("ModuleTwo")
            .WithOpenApi()
            .RequireAuthorization(policyNames: CookieAuthenticationDefaults.AuthenticationScheme + ",OpenIddict.Validation.AspNetCore");
    }

    // [FeatureGroupName("Weather")]
    private WeatherForecast[] WeatherGet([FromServices] ILogger<WeatherForecastEndpoints> logger)
    {
        var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" };
        var forecast = Enumerable.Range(1, 5).Select(index =>
                new WeatherForecast
                (
                    DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                    Random.Shared.Next(-20, 55),
                    summaries[Random.Shared.Next(summaries.Length)]
                ))
            .ToArray();
        logger.LogInformation("WeatherForecast request execute at [{Time}].", DateTime.UtcNow);
        return forecast;
    }
}

Версия 2.0.0

  • Больше не требуется вливать зависимость IServiceCollection в метод ConfigureServices. Теперь достаточно только WebApplicationBuilder. Следовательно при переходе на версию 2.0.0 нужно просто удалить лишние зависимости. Например, регистрация FluentValidation это выглядит так:
/// <summary>
/// FluentValidation registration as Application definition
/// </summary>
public class FluentValidationDefinition : AppDefinition
{
    /// <summary>
    /// Configure services for current application
    /// </summary>
    /// <param name="builder"></param>
    public override void ConfigureServices(WebApplicationBuilder builder)
    {
        builder.Services.Configure<ApiBehaviorOptions>(options =>
        {
            options.SuppressModelStateInvalidFilter = true;
        });

        builder.Services.AddValidatorsFromAssembly(typeof(Program).Assembly);
    }
}
  • Регистрация стала гораздо проще.
builder.AddDefinitions(typeof(Program));

Установка nuget-пакета

Можно воспользоваться инструментов Visual Studio:

image1

Или можно просто прописать в файле проекта, но тогда надо будет подставить правильную версию пакета. Посмотреть последнюю актуальную версию можно на nuget.org.

image2

Создание AppDefinitions

Создайте папку Definitions в вашем проекте. В папке создайте ContainerDefinition и унаследуйте его от AppDefinition, как показано ниже на картинке. После этого сделайте переопределение метода ConfigureServices и/или других методов и свойств.

image3

На этой картинке переопределено два метода:

image4

Подключите ваши определения как показано на этой картинке:

image6

Таких определений (наследников от AppDefinition) может быть сколько угодно (конечно же в разумных пределах). После старта приложения вы увидите (если включен уровень логирования Debug) список всех подключенных определений (AppDefinition). Например, в моём случае их 18.

image5

Фильтрация и порядок

У каждого из созданных вами наследников от AppDefinition есть свойство Enabled и OrderIndex. Угадайте, что можно с ними (с AppDefinitionами) сделать?

An English

Application Definitions base classes. The small but very helpful package that can help you to organize your ASP.NET Core application.

You can find more information in my blog Nimble Framework

Product Compatible and additional computed target framework versions.
.NET 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 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 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.
  • net6.0

    • No dependencies.
  • net8.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on Calabonga.AspNetCore.AppDefinitions:

Repository Stars
Calabonga/Microservice-Template
Templates for microservice architecture. Nimble Microservice Framework contains two modules. The first with OpenIddict and the second without OpenIddict. Templates are built on ASP.NET Core platform with different versions Core3.1, NET6, NET7 and NET8. You can create a new project extremely fast: in Visual Studio, Rider, dotnet CLI.
Version Downloads Last updated
2.4.3 85 4/11/2024
2.4.2 83 4/11/2024
2.4.1 3,299 1/10/2024
2.4.0 1,360 11/22/2023
2.3.0 188 11/6/2023
2.2.0 4,817 8/10/2023
2.1.0 239 8/6/2023
2.0.0 715 6/26/2023
1.3.0 3,280 4/21/2023
1.2.2 1,570 1/19/2023
1.2.1 318 12/30/2022
1.2.0 515 10/3/2022
1.1.0 702 9/19/2022
1.0.0 382 9/4/2022

Split order index fot Services and for Application definitions.