69 lines
2.4 KiB
C#
69 lines
2.4 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using MongoDB.Bson.Serialization;
|
|
using ExpenseTracker.Application.Common.Interfaces.Repositories;
|
|
using ExpenseTracker.Domain.Entities;
|
|
using ExpenseTracker.Persistence.MongoDb;
|
|
using ExpenseTracker.Persistence.PostgreSQL;
|
|
using ExpenseTracker.Persistence.MongoDb.Repositories;
|
|
using ExpenseTracker.Persistence.Serializers;
|
|
using ExpenseTracker.Persistence.PostgreSQL.Repositories;
|
|
using ExpenseTracker.Application.Common.Interfaces;
|
|
|
|
namespace ExpenseTracker.Persistence;
|
|
|
|
public static class DependencyInjection
|
|
{
|
|
public static IServiceCollection AddPersistence(this IServiceCollection services, IConfiguration configuration)
|
|
{
|
|
var databaseName = configuration["Database:Type"];
|
|
|
|
if (databaseName.Equals("mongodb"))
|
|
{
|
|
services.AddMongoDb();
|
|
return services;
|
|
}
|
|
|
|
if (databaseName.Equals("postgresql"))
|
|
{
|
|
services.AddPostgreSQL(configuration);
|
|
return services;
|
|
}
|
|
|
|
// TODO: Refactor to use database type enum
|
|
|
|
throw new ArgumentException(
|
|
$"Unsupported database type specified in configuration. " +
|
|
$"Supported types: mongodb postgresql");
|
|
}
|
|
|
|
private static IServiceCollection AddMongoDb(this IServiceCollection services)
|
|
{
|
|
BsonSerializer.RegisterSerializer<Account>(new AccountSerializer());
|
|
BsonSerializer.RegisterSerializer<Transaction>(new TransactionSerializer());
|
|
|
|
services.AddScoped<MongoDbContext>();
|
|
services.AddScoped<IUnitOfWork, MongoDbUnitOfWork>();
|
|
services.AddScoped<IAccountRepository, AccountMongoDbRepository>();
|
|
services.AddScoped<ITransactionRepository, TransactionMongoDbRepository>();
|
|
|
|
return services;
|
|
}
|
|
|
|
private static IServiceCollection AddPostgreSQL(this IServiceCollection services, IConfiguration configuration)
|
|
{
|
|
services.AddDbContext<ApplicationDbContext>(options =>
|
|
{
|
|
options.UseNpgsql(configuration["Database:ConnectionString"]);
|
|
});
|
|
|
|
services.AddScoped<ApplicationDbContext>();
|
|
|
|
// services.AddScoped<ITransactionRepository, ExpensePostgreSQLRepository>();
|
|
// services.AddScoped<IAccountRepository, BudgetPostgreSQLRepository>();
|
|
|
|
return services;
|
|
}
|
|
}
|