Apr 08 2024
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddCustomServices(
this IServiceCollection services)
{
services.AddScoped<IMyService, MyService>();
services.AddSingleton<IOtherService, OtherService>();
// ... other services
return services;
}
}
builder.Services.AddCustomServices();
public static IServiceCollection AddDatabase(
this IServiceCollection services,
string connectionString)
{
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connectionString));
return services;
}
public static IServiceCollection AddIdentityServices(
this IServiceCollection services)
{
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<MyDbContext>()
.AddDefaultTokenProviders();
return services;
}
public static IServiceCollection AddJwtAuthentication(
this IServiceCollection services, IConfiguration configuration)
{
var jwtSettings = configuration.GetSection("JwtSettings");
var key = Encoding.ASCII.GetBytes(jwtSettings.GetValue<string>("Secret"));
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
return services;
}
public static IServiceCollection AddCorsPolicy(
this IServiceCollection services,
string policyName,
string[] allowedOrigins)
{
services.AddCors(options =>
{
options.AddPolicy(policyName,
builder => builder.WithOrigins(allowedOrigins)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
return services;
}
builder.Services.AddDatabase(Configuration.GetConnectionString("DefaultConnection"));
builder.Services.AddIdentityServices();
builder.Services.AddJwtAuthentication(Configuration);
builder.Services.AddCorsPolicy("MyPolicy", new[] { "http://example.com" });
// ... other configurations
Join 13,250+ subscribers to improve your .NET Knowledge.
Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.
Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.
Subscribe to the TheCodeMan.net and be among the 13,250+ subscribers gaining practical tips and resources to enhance your .NET expertise.