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
{
///
/// Adds dbcontext and all repositories in repository namespace
///
/// service collection
/// configuration
public static void AddDbServices(this IServiceCollection collection, IConfiguration config)
{
string dbConnectionString = config.GetConnectionString("DefaultConnection");
collection.AddDbContext(opt =>
{
opt.UseNpgsql(dbConnectionString);
});
Type[] repositories = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => t.IsClass && !t.IsAbstract && (t.Namespace?.Contains(nameof(DBConnection.Repositories)) ?? false) && 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);
}
}
}
}