Gurung.ServicesRegister 1.0.0

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

// Install Gurung.ServicesRegister as a Cake Tool
#tool nuget:?package=Gurung.ServicesRegister&version=1.0.0                

Dynamic Service Registration Library .NET Core

This library provides a modular and flexible approach for dynamically registering services in a .NET Core application. By breaking down the registration logic into specialized classes, the library enhances code maintainability and reusability. It supports configuration for services, databases, identity, repositories, and JWT authentication in a clear, manageable way.

Features

  • Modular Service Registration: Register services, repositories, identity, and database contexts in separate classes for better maintainability.
  • Flexible Database Configuration: Supports database context registration with DbContext.
  • Identity and Authentication: Easily set up Identity Core and JWT authentication.
  • Scoped and Transient Services: Supports registration of scoped and transient services.

Installation

Install the package via NuGet:

 NuGet\Install-Package Gurung.ServicesRegister

Usage

Program.cs

Here is an example of how to use the library in your Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
// Register services using the dynamic service registration library
builder.Services.AddServiceRegister(builder.Configuration);

var app = builder.Build();
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.Run();

How It Works

The library supports two main ways to organize and modularize service registration:

Decentralized (Modular) Service Registration:

The library allows you to split the service registration logic into separate classes based on specific concerns, such as:

  • Database Registration
  • Identity and Authentication
  • Repository Registration
  • Service-Specific Registration
  • Service-Specific Registration with Configuration
Example of Modular Registrations:
1. DatabaseRegistration:

This class registers essential services like HttpContextAccessorand JWT settings

public class ServiceRegistration : IServicesRegistrationWithConfig
{
    public void AddServices(IServiceCollection services, IConfiguration configuration)
    {
        services.AddCarter(c => c.WithValidatorLifetime(ServiceLifetime.Scoped));
        services.AddHttpContextAccessor();
        services.Configure<JwtTokenSetting>(configuration.GetSection("JwtSettings"));
        services.AddScoped<TenantMigrationService>();
        RepositoryServiceRegistration.ConfigureServices(services);
    }
}
2. DatabaseRegistration:

This class is responsible for registering the database contexts.

public class DatabaseRegistration : IDbServiceRegistration
{
    public void AddServices(IServiceCollection services, IConfiguration configuration)
    {
        services.AddDbContext<MainDbContext>(options => options.UseSqlServer(
            configuration.GetConnectionString("DefaultConnection"),
            sqlOptions => sqlOptions.MigrationsAssembly(typeof(MainDbContext).Assembly.FullName)));
        services.AddDbContextFactory<TenantDbContext>();
    }
}
3. IdentityRegistration:

This class configures Identity Core and authentication mechanisms, including JWT and cookie authentication. Here is an example of how to use the library in your Program.cs:

public class IdentityRegistration : IIdentityServicesRegistration
{
    public void AddServices(IServiceCollection services, IConfiguration configuration)
    {
        services.AddIdentityCore<ApplicationUser>()
                .AddRoles<ApplicationRole>()
                .AddEntityFrameworkStores<MainDbContext>()
                .AddDefaultTokenProviders();

        services.AddAuthorization();
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidIssuer = configuration["JwtSettings:Issuer"],
                        ValidAudience = configuration["JwtSettings:Issuer"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSettings:Key"])),
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true
                    };
                });
    }
}
4. RepositoryRegistration:

This class registers repositories needed for your application.

public class RepositoryRegistration : IRepositoriesRegistration
{
    public void AddServices(IServiceCollection services)
    {
        services.AddScoped<ICategoriesRepository, CategoriesRepository>();
        services.AddScoped<ITenantsRepository, TenantsRepository>();
    }
}
5. ServicesRegistration:

This class registers other application services.

public class ServicesRegistration : IServicesRegistration
{
    public void AddServices(IServiceCollection services)
    {
        services.AddScoped<ICurrentTenantService, CurrentTenantService>();
        services.AddScoped<ITenantUserManagementService, TenantUserManagementService>();
        services.AddTransient<ITokenService, TokenService>();
    }
}

Centralized Service Registration in a Single Class

1. ServicesRegistration:

All the services, such as database contexts, identity, repositories, and authentication, can be registered centrally in a single class.

Example:
public class ServiceRegistration : IServicesRegistrationWithConfig
{
    public void AddServices(IServiceCollection services, IConfiguration configuration)
    {
        services.AddCarter(c => c.WithValidatorLifetime(ServiceLifetime.Scoped));
        services.AddHttpContextAccessor();  

        ConfigureDbContext(services, configuration);
        services.ConfigureIdentity(configuration);

        services.Configure<JwtTokenSetting>(configuration.GetSection("JwtSettings"));

        services.AddScoped<TenantMigrationService>();
        RepositoryServiceRegistration.ConfigureServices(services);

        AddServices(services);
        AddRepositories(services);
    }

    internal IServiceCollection AddServices(IServiceCollection services)
    {
        services.AddScoped<ICurrentTenantService, CurrentTenantService>();
        services.AddScoped<ITenantUserManagementService, TenantUserManagementService>();
        services.AddScoped<ITenancyManagerService, TenancyManagerService>();
        services.AddTransient<ITokenService, TokenService>();
        return services;
    }

    internal void AddRepositories(IServiceCollection services)
    {
        services.AddTransient<ICategoriesRepository, CategoriesRepository>();
        services.AddScoped<ITenantsRepository, TenantsRepository>();
    }

    internal IServiceCollection ConfigureDbContext(IServiceCollection services, IConfiguration configuration)
    {
        services.AddScoped<ITenantContextProvider, TenantContextProvider>();
        services.AddDbContext<MainDbContext>(options =>
        {
            options.UseSqlServer(
                configuration.GetConnectionString("DefaultConnection"),
                sqlOptions => sqlOptions.MigrationsAssembly(typeof(MainDbContext).Assembly.FullName));
        });
        services.AddDbContextFactory<TenantDbContext>();
        services.AddScoped<ITenantDbContext>(provider => provider.GetRequiredService<TenantDbContext>());
        return services;
    }
}

2. Identity Configuration:

The identity configuration is extracted into an extension method to simplify the service registration process in ServiceRegistration.

public static class IdentityConfigureServiceExtension
{
    public static IServiceCollection ConfigureIdentity(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddIdentityCore<ApplicationUser>()
                .AddRoles<ApplicationRole>()
                .AddSignInManager<SignInManager<ApplicationUser>>()
                .AddEntityFrameworkStores<MainDbContext>()
                .AddDefaultTokenProviders();

        services.AddIdentityCore<TenantUser>()
                .AddSignInManager<SignInManager<TenantUser>>()
                .AddRoles<TenantRole>()
                .AddEntityFrameworkStores<TenantDbContext>()
                .AddDefaultTokenProviders();

        services.AddAuthorization();
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddCookie(IdentityConstants.ApplicationScheme, o =>
        {
            o.LoginPath = new PathString("/Account/Login");
            o.Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync
            };
        })
        .AddJwtBearer(x =>
        {
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidIssuer = configuration["JwtSettings:Issuer"],
                ValidAudience = configuration["JwtSettings:Issuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSettings:Key"])),
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true
            };
        });

        return services;
    }
}

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

License

This package is free to use for any purpose.

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 was computed.  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.0.0 105 10/21/2024