40 lines
1.5 KiB
C#
40 lines
1.5 KiB
C#
using System.Reflection;
|
|
using DBConnection.Repositories.Interfaces;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace DBConnection.Extensions;
|
|
|
|
public static class BuilderExtensions
|
|
{
|
|
/// <summary>
|
|
/// Adds dbcontext and all repositories in repository namespace
|
|
/// </summary>
|
|
/// <param name="collection">service collection</param>
|
|
/// <param name="config">configuration</param>
|
|
public static void AddDbServices(this IServiceCollection collection, IConfiguration config)
|
|
{
|
|
string dbConnectionString = config.GetConnectionString("DefaultConnection");
|
|
collection.AddDbContext<AppDbContext>(opt =>
|
|
{
|
|
opt.UseNpgsql(dbConnectionString);
|
|
});
|
|
Type[] repositories = Assembly.GetExecutingAssembly().GetTypes()
|
|
.Where(t => t.IsClass && !t.IsAbstract && t.Namespace.Contains(nameof(DBConnection.Repositories)) && typeof(IRepository).IsAssignableFrom(t)).ToArray();
|
|
foreach (var repo in repositories)
|
|
{
|
|
var repoInterface = repo.GetInterfaces()
|
|
.FirstOrDefault(repoInterface => typeof(IRepository).IsAssignableFrom(repoInterface) && repoInterface != typeof(IRepository));
|
|
if (repoInterface != null)
|
|
{
|
|
collection.AddScoped(repoInterface, repo);
|
|
}
|
|
else
|
|
{
|
|
collection.AddScoped(repo);
|
|
}
|
|
}
|
|
|
|
}
|
|
} |