Basics setup, going to change how repos work
This commit is contained in:
40
DBConnection/Extensions/BuilderExtensions.cs
Normal file
40
DBConnection/Extensions/BuilderExtensions.cs
Normal file
@@ -0,0 +1,40 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user