DRN.Framework.Utils 0.4.0

The ID prefix of this package has been reserved for one of the owners of this package by NuGet.org. Prefix Reserved
dotnet add package DRN.Framework.Utils --version 0.4.0
NuGet\Install-Package DRN.Framework.Utils -Version 0.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="DRN.Framework.Utils" Version="0.4.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add DRN.Framework.Utils --version 0.4.0
#r "nuget: DRN.Framework.Utils, 0.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 DRN.Framework.Utils as a Cake Addin
#addin nuget:?package=DRN.Framework.Utils&version=0.4.0

// Install DRN.Framework.Utils as a Cake Tool
#tool nuget:?package=DRN.Framework.Utils&version=0.4.0

master develop Quality Gate Status

Security Rating Maintainability Rating Reliability Rating Vulnerabilities Bugs Lines of Code Coverage

DRN.Framework.Utils package contains common codes for other DRN.Framework packages and projects developed with DRN.Framework.

Module

DRN.Utils can be added with following module

namespace DRN.Framework.Utils;

public static class UtilsModule
{
    public static IServiceCollection AddDrnUtils(this IServiceCollection collection)
    {
        collection.AddServicesWithAttributes();

        return collection;
    }
}

Dependency Injection with Attributes

Each module should be created in the assembly that will be scanned.

public static class InfraModule
{
    public static IServiceCollection AddSampleInfraServices(this IServiceCollection sc)
    {
        sc.AddServicesWithAttributes();

        return sc;
    }
}

Services resolution for attribute based services can be validated with a single line.

serviceProvider.ValidateServicesAddedByAttributes();

Attribute based dependency injection reduces wiring efforts and helps developer to focus on developing. This approach also improves service resolution validation during startup and integration testing.

    [Theory]
    [DataInlineContext]
    public void Validate_Sample_Dependencies(TestContext context)
    {
        context.ServiceCollection.AddSampleApplicationServices();
        context.ServiceCollection.AddSampleInfraServices();
        context.ValidateServices();
    }

Lifetime Attributes

Example attribute usage:

[Transient<IIndependent>]
public class Independent : IIndependent
{
}

Following attributes marks services with a lifetime and when service collection called with AddServicesWithAttributes method in the assembly marked belong they are automatically added.

namespace DRN.Framework.Utils.DependencyInjection.Attributes;

public class LifetimeAttribute<TService>(ServiceLifetime serviceLifetime, bool tryAdd = true, object? key = null)
    : LifetimeAttribute(serviceLifetime, typeof(TService), tryAdd, key);

public class LifetimeWithKeyAttribute<TService>(ServiceLifetime serviceLifetime, object key, bool tryAdd = true)
    : LifetimeAttribute(serviceLifetime, typeof(TService), tryAdd, key);

public class ScopedAttribute<TService>(bool tryAdd = true) : LifetimeAttribute<TService>(ServiceLifetime.Scoped, tryAdd);

public class ScopedWithKeyAttribute<TService>(object key, bool tryAdd = true) : LifetimeWithKeyAttribute<TService>(ServiceLifetime.Scoped, key, tryAdd);

public class TransientAttribute<TService>(bool tryAdd = true) : LifetimeAttribute<TService>(ServiceLifetime.Transient, tryAdd);

public class TransientWithKeyAttribute<TService>(object key, bool tryAdd = true) : LifetimeWithKeyAttribute<TService>(ServiceLifetime.Transient, key, tryAdd);

public class SingletonAttribute<TService>(bool tryAdd = true) : LifetimeAttribute<TService>(ServiceLifetime.Singleton, tryAdd);

public class SingletonWithKeyAttribute<TService>(object key, bool tryAdd = true) : LifetimeWithKeyAttribute<TService>(ServiceLifetime.Singleton, key, tryAdd);

HasServiceCollectionModuleAttribute

Attributes derived from HasServiceCollectionModuleAttribute can be used to mark custom service collection modules. In the following example HasDrnContextServiceCollectionModuleAttribute marks DrnContext<TContext> and its service collection module. This way dbContexts inherited from DrnContext doesn't need a lifetime attribute and they can be registered by AddServicesWithAttributes with their custom factory.

This offers following flexibility:

  1. ServiceCollectionModule of DrnContexts are defined in DRN.Framework.EntityFramework
  2. Inherited dbContexts are defined in user defined projects and points a module in another project.
  3. AddServicesWithAttributes extension method defined in DRN.Framework.Utils registers them without depending DRN.Framework.EntityFramework project
public class HasDrnContextServiceCollectionModuleAttribute : HasServiceCollectionModuleAttribute
{
    static HasDrnContextServiceCollectionModuleAttribute() =>
        ModuleMethodInfo = typeof(ServiceCollectionExtensions)
            .GetMethod(nameof(ServiceCollectionExtensions.AddDbContextsWithConventions))!;

    public override async Task PostStartupValidationAsync(object service, IServiceProvider serviceProvider)
    {
        var appSettings = serviceProvider.GetRequiredService<IAppSettings>();
        var migrate = appSettings.Configuration.GetValue(DbContextConventions.AutoMigrateDevEnvironmentKey, false);
        if (appSettings.Environment == AppEnvironment.Development && migrate && service is DbContext context)
            await context.Database.MigrateAsync();
    }
}

[HasDrnContextServiceCollectionModule]
public abstract class DrnContext<TContext> : DbContext, IDesignTimeDbContextFactory<TContext>, IDesignTimeServices where TContext : DbContext, new()
{
...

HasServiceCollectionModuleAttribute's PostStartupValidationAsync will be called when,

  • ValidateServicesAddedByAttributes extension method called from service provider if all services resolved successfully.
  • For instance, DrnContext can apply EF migrations after service provider services resolved successfully.

Configurations

Following configuration sources can be used to add configurations from different sources

  • JsonSerializerConfigurationSource converts poco objects to configuration
  • RemoteJsonConfigurationSource fetches remote configuration (experimental and incomplete)

Following MountedSettingsConventions will be added to configuration.

  • /appconfig/json-settings json files will be added to configuration if any exist
  • /appconfig/key-per-file-settings files will be added to configuration if any exist
  • IMountedSettingsConventionsOverride overrides default /appconfig location if added to service collection before host built
namespace DRN.Framework.Utils.Settings.Conventions;

public static class MountedSettingsConventions
{
    public const string DefaultMountDirectory = "/appconfig";
    
    public static string JsonSettingsMountDirectory(string? mountDirectory = null)
        => Path.Combine(mountDirectory ?? DefaultMountDirectory, "json-settings");
    public static string KeyPerFileSettingsMountDirectory(string? mountDirectory = null)
        => Path.Combine(mountDirectory ?? DefaultMountDirectory, "key-per-file-settings");

    public static DirectoryInfo JsonSettingDirectoryInfo(string? mountDirectory = null)
        => new(JsonSettingsMountDirectory(mountDirectory));
}

public interface IMountedSettingsConventionsOverride
{
    string? MountedSettingsDirectory { get; }
}

AppSettings

Following IAppSettings interface is defined and can be used to obtain appsettings. It has utility methods that allow fail fast.

namespace DRN.Framework.Utils.Settings;

public interface IAppSettings
{
    AppEnvironment Environment { get; }
    IConfiguration Configuration { get; }
    bool TryGetConnectionString(string name, out string connectionString);
    string GetRequiredConnectionString(string name);
    bool TryGetSection(string key, out IConfigurationSection section);
    IConfigurationSection GetRequiredSection(string key);
    T? GetValue<T>(string key);
    T? GetValue<T>(string key, T defaultValue);
    T? Get<T>(string key, Action<BinderOptions>? configureOptions = null);
    ConfigurationDebugView GetDebugView();
}

ExtensionMethods

  • ServiceCollectionExtensions
    • ReplaceInstance
    • ReplaceTransient
    • ReplaceScoped
    • ReplaceSingleton
    • GetAllAssignableTo<TService>
  • StringExtensions
    • ToStream
  • TypeExtensions
    • MakeGenericMethod
  • AssemblyExtensions
    • GetTypesAssignableTo

Semper Progredi: Always Progressive

Commit Info

Author: Duran Serkan KILIÇ
Date: 2024-05-19 23:25:32 +0300
Hash: 2c6009a829defc78647603ba828566ea52aeb989

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 (2)

Showing the top 2 NuGet packages that depend on DRN.Framework.Utils:

Package Downloads
DRN.Framework.EntityFramework The ID prefix of this package has been reserved for one of the owners of this package by NuGet.org.

DRN.Framework.EntityFramework provides DrnContext with conventions to develop rapid and effective domain models. ## Commit Info Author: Duran Serkan KILIÇ Date: 2024-05-19 23:25:32 +0300 Hash: 2c6009a829defc78647603ba828566ea52aeb989

DRN.Framework.Hosting The ID prefix of this package has been reserved for one of the owners of this package by NuGet.org.

DRN.Framework.Hosting ## Commit Info Author: Duran Serkan KILIÇ Date: 2024-05-19 23:25:32 +0300 Hash: 2c6009a829defc78647603ba828566ea52aeb989

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.4.0 72 5/19/2024
0.4.0-preview006 64 5/19/2024
0.4.0-preview005 55 5/12/2024
0.4.0-preview004 53 5/12/2024
0.4.0-preview003 56 5/11/2024
0.4.0-preview002 66 5/8/2024
0.4.0-preview001 82 5/5/2024
0.3.1-preview001 85 4/26/2024
0.3.0 86 4/23/2024
0.3.0-preview002 72 4/23/2024
0.3.0-preview001 88 4/23/2024
0.2.2-preview010 90 4/11/2024
0.2.2-preview009 90 3/18/2024
0.2.2-preview008 96 3/18/2024
0.2.2-preview007 89 3/16/2024
0.2.2-preview006 84 3/11/2024
0.2.2-preview005 85 3/10/2024
0.2.2-preview004 83 3/10/2024
0.2.2-preview003 96 1/22/2024
0.2.2-preview002 68 1/18/2024
0.2.2-preview001 83 1/14/2024
0.2.1 158 1/7/2024
0.2.0 126 12/31/2023
0.2.0-preview009 84 12/31/2023
0.2.0-preview008 93 12/30/2023
0.2.0-preview007 98 12/28/2023
0.2.0-preview006 93 12/27/2023
0.2.0-preview005 93 12/25/2023
0.2.0-preview004 83 12/23/2023
0.2.0-preview003 69 12/20/2023
0.2.0-preview002 83 12/19/2023
0.2.0-preview001 83 12/18/2023
0.1.0 153 11/26/2023
0.1.0-preview013 96 11/26/2023
0.1.0-preview012 76 11/20/2023
0.1.0-preview011 96 11/19/2023
0.1.0-preview010 93 10/30/2023
0.1.0-preview009 92 10/29/2023
0.1.0-preview008 101 10/27/2023
0.1.0-preview007 83 10/11/2023
0.1.0-preview006 97 10/9/2023
0.1.0-preview005 96 10/8/2023
0.1.0-preview004 99 10/8/2023
0.1.0-preview003 99 10/3/2023
0.1.0-preview002 102 10/3/2023
0.1.0-preview001 103 10/2/2023

Not every version includes changes, features or bug fixes. This project can increment version to keep consistency with other DRN.Framework projects.  

## Version 0.4.0

My family celebrates the enduring legacy of Mustafa Kemal Atatürk's enlightenment ideals. This release is dedicated to 19 May Commemoration of Atatürk, Youth and Sports Day.

### Breaking Changes

* AttributeSpecifiedServiceCollectionModule renamed as AttributeSpecifiedServiceModule
* HasServiceCollectionModuleAttribute renamed as ServiceRegistrationAttribute
* HasDrnContextServiceCollectionModuleAttribute renamed as DrnContextServiceRegistrationAttribute
* ServiceRegistrationAttribute MethodInfo property replaced with ServiceRegistration method to make usage strongly typed and support inheritance

### New Features

* DrnAppFeatures property added to IAppSettings
 * InternalRequestHttpVersion can be set as "1.1" or "2.0"
 * InternalRequestProtocol can be set as "http" or "https ""
* IInternalRequest and InternalRequest added to generate internal Flurl requests with configurable **Linkerd compatible** sensible defaults
* HttpResponse and following flurl response extensions added to fluently get strongly typed response and flurl response together:
 * ToStringAsync
 * ToBytesAsync
 * ToStreamAsync
 * ToJsonAsync<TResponse>

## Version 0.3.0

My family celebrates the enduring legacy of Mustafa Kemal Atatürk's enlightenment ideals. This release is dedicated to 23 April National Sovereignty and Children's Day.

### New Features
* AppSettings now has GetDebugView() method that returns ConfigurationDebugView
 * ConfigurationDebugView has ToSummary() method that returns human friendly configuration summary model.
* AppSettings now has GetValue<> and Get<> methods to get values from configuration
* MountedSettingsConventions added.
 * /appconfig/json-settings json files will be added to configuration if any exist
 * /appconfig/key-per-file-settings files will be added to configuration if any exist
 * IMountedSettingsConventionsOverride overrides default /appconfig location if added to service collection before host built
* HasServiceCollectionModuleAttribute has PostStartupValidationAsync when,
 * ValidateServicesAddedByAttributes extension method called from service provider,
 * PostStartupValidationAsync will be called if all services resolved successfully.
 * For instance, DrnContext can apply migrations after service provider services resolved successfully.
* ScopedLog and IScopedLog added to aggregate related log within a scope such as a http request.

## Version 0.2.0

### Breaking Changes

* LifetimeContainer renamed as DrnServiceContainer
* Lifetime attributes moved to DRN.Framework.Utils.DependencyInjection.Attributes namespace

### New Features

* JsonSerializerConfigurationSource added to add dotnet objects to configuration
* RemoteJsonConfigurationSource added to remote settings to configuration (experimental)
* ConnectionStringsCollection added as poco model to serialize connection strings
* StringExtensions added
 * ToStream method added to convert strings to in memory stream
* HasServiceCollectionModuleAttribute added

## Version 0.1.0

### Breaking Changes

### New Features

* AppSettings added
* ServiceCollectionExtensions added
 * ReplaceInstance
 * ReplaceTransient
 * ReplaceScoped
 * ReplaceSingleton
* Attribute based dependency injection added
 * ScopedAttribute, TransientAttribute, SingletonAttribute and LifetimeAttribute added
 * ScopedWithKeyAttribute, TransientWithKeyAttribute, SingletonWithKeyAttribute and LifetimeWithKeyAttribute added
 * ServiceCollection AddServicesWithAttributes extension added
 * ServiceProvider ValidateServicesAddedByAttributes extension added

### Bug Fixes

---
**Semper Progredi: Always Progressive**  
 
## Commit Info  
Author: Duran Serkan KILIÇ  
Date: 2024-05-19 23:25:32 +0300  
Hash: 2c6009a829defc78647603ba828566ea52aeb989