Repository pattern with multiple databases - c#

I am using repository pattern on EF Core and Autofac in a windows service.
I have a service that needs to connect with the some dozen databases which have the same schema (same dbcontext) but only different data.
How can I achieve this in my service using Autofac? Belo
public class ReportRepository : IReportRepository
{
private readonly ReportDbContext dbContext;
public ReportRepository(ReportDbContext dbContext)
{
this.dbContext = dbContext
}
public SomeModel GetData()
{
return dbContext.SalesData;
}
}
public class ReportService : IReportService
{
private readonly IReportRepository reportRepositoryEUServer;
public ReportService(IReportRepository reportRepositoryEUServer)
{
this.reportRepositoryEUServer = reportRepositoryEUServer
}
public SomeModelDto GenerateReport()
{
var euData = reportRepositoryEUServer.GetData();
// I need to call other servers (e.g LATAM) here and get the data and aggregate them with euData
}
}

Create base context including all settings, dbsets etc:
public abstract class BaseContext : DbContext
{
public BaseContext(DbContextOptions options)
: base(options)
{ }
public DbSet<object> FirstSet { get; set; }
...
}
inherit from BaseContext for both DBs
public class LATAMContext : BaseContext
{
public LATAMContext(DbContextOptions<LATAMContext> options) : base(options)
{
}
}
public class EUContext : BaseContext
{
public EUContext(DbContextOptions<EUContext> options) : base(options)
{
}
}
and register both in Startup.cs
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddDbContext<LATAMContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LATAMConnectionString")));
services.AddDbContext<EUContext>(options => options.UseSqlServer(Configuration.GetConnectionString("EUConnectionString")));
// Autofac
var builder = new ContainerBuilder();
// needed only if you plan to inject ICollection<BaseContext>
builder.RegisterType<LATAMContext>().As<BaseContext>();
builder.RegisterType<EUContext>().As<BaseContext>();
builder.Populate(services);
return new AutofacServiceProvider(builder.Build());
}
add connection strings in appsettings.json
"ConnectionStrings": {
"LATAMConnectionString": "Server=(localdb)\\mssqllocaldb;Database=ContosoUniversity1;Trusted_Connection=True;MultipleActiveResultSets=true",
"EUConnectionString": "Server=(localdb)\\mssqllocaldb;Database=ContosoUniversity1;Trusted_Connection=True;MultipleActiveResultSets=true"
}
and now you can inject both contexts
public class ReportRepository : IReportRepository
{
private readonly LATAMContext latamDbContext;
private readonly EUContext euDbContext;
public ReportRepository(LATAMContext latamDbContext, EUContext euDbContext)
{
this.latamDbContext = latamDbContext;
this.euDbContext = euDbContext;
}
}
or if you plan to inject collection of contexts
public class ReportRepository : IReportRepository
{
private readonly ICollection<BaseContext> dbContexts;
public ReportRepository(ICollection<BaseContext> dbContexts)
{
this.dbContexts = dbContexts;
}
}
to access specific context
var _euContext = dbContexts.FirstOrDefault(x => x is EUContext) as EUContext;
var _latamContext = dbContexts.FirstOrDefault(x => x is LATAMContext) as LATAMContext;

Related

How to use Dependency inject when using a service layer with Entity Framework Core?

My project is an ASP.NET Core 6 Web API. I am using Entity Framework Core and built-in dependency injection.
Program.cs:
var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddDbContext<myService>(options => options.UseSqlServer(ConnStr));
builder.Services.AddDbContext<anotherService>(options => options.UseSqlServer(anotherConnStr));
...
myController.cs:
public class myController : ControllerBase
{
private readonly myService _context;
public myController(myService context)
{
_context = context;
}
// ... Routes use either db models directly or methods from myService
}
myService.cs:
I'm using myContext as a base class so I can access the db tables directly in my controller.
Any better way to do this? db = this;
How do I inject this service?
private readonly anotherService anotherdb;
public class myService : myContext
{
private readonly myContext db;
private readonly anotherService anotherdb;
public myService(DbContextOptions<myService> options) : base(options)
{
// inject myContext, works but doesn't feel right.
db = this;
// how do I inject this?
anotherdb = new anotherService();
}
public IQueryable<mytable> Getdata()
{
var q = from s in db.mytable
select s;
return q;
}
// ...
}
myContext.cs:
public partial class myContext : DbContext
{
public myContext()
{
}
public myContext(DbContextOptions<myContext> options)
: base(options)
{
}
protected myContext(DbContextOptions options)
: base(options)
{
}
// ...
}
I have lots of services all with the same design, how can I inject another service into myService.cs?

System.ArgumentNullException when GetDbContext in constructor

I'm trying to use Entity Framework Core with ASP.NET Boilerplate .NET Core, but I don't want to use Repository built-in functions.
There is a problem with my DB context; it keeps returning:
System.ArgumentNullException: 'Value cannot be null.'
for the DbContext instance as shown below:
public class MainProjectsAppService : ApplicationService
{
private readonly DecentralizationDbContext _ctx;
public MainProjectsAppService(IDbContextProvider<DecentralizationDbContext> dbContextProvider)
{
_ctx = dbContextProvider.GetDbContext();
}
public void CustomizedCreateMainProject(MainProject mainProject)
{
MainProject customizedMainProject = new MainProject
{
...
};
_ctx.MainProjects.Add(customizedMainProject);
_ctx.SaveChanges();
}
}
Below is the DbContext class code:
namespace Decentralization.EntityFrameworkCore
{
public class DecentralizationDbContext : AbpZeroDbContext<Tenant, Role, User, DecentralizationDbContext>
{
/* Define a DbSet for each entity of the application */
public DbSet<MainProject> MainProjects { get; set; }
public DecentralizationDbContext(DbContextOptions<DecentralizationDbContext> options)
: base(options)
{
}
}
}
Do not call dbContextProvider.GetDbContext() in the constructor.
Define a getter instead:
public class MainProjectsAppService : ApplicationService
{
private readonly IDbContextProvider<DecentralizationDbContext> _dbContextProvider;
private DecentralizationDbContext _ctx => _dbContextProvider.GetDbContext();
public MainProjectsAppService(IDbContextProvider<DecentralizationDbContext> dbContextProvider)
{
_dbContextProvider = dbContextProvider;
}
}
Reference: aspnetboilerplate/aspnetboilerplate#4809

How to register a class to IoC in Prism

I write an application with WPF. I use the Prism library with IoC as Prism.DryIoC.
I have an AppDbContext.cs class to declare the connection string to the database (here is MongoDB)
public class AppDbContext : BaseMongoRepository
{
public AppDbContext(string connectionString, string databaseName = null) : base(connectionString, databaseName)
{
}
}
I have a class MyService.cs that uses the AppDbContext class, I declare in the constructor.
public class MyService : IMyService
{
private AppDbContext _dbContext;
public IdentifierRepository(AppDbContext dbContext)
{
_dbContext = dbContext;
}
public void AddCustomer(Customer model)
{
// Some code....
_dbContext.Add(model);
}
}
In the App.xaml.cs class I override the method
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterSingleton<IAuthenticationService, AuthenticationService>();
// MongoDB
var connectionString = SharedCommon.LocalAppSettings.Database.ConnectionString;
var database = SharedCommon.LocalAppSettings.Database.DatabaseName;
// How to register class MyService.cs here?
// I dont known.
containerRegistry<MyService>(() => new MyService(new AppDbContext(connectionString, database))); // Wrong code
}
You can find all the registration methods here.
For singleton MyService:
var myService = new MyService(new AppDbContext(connectionString, database)));
containerRegistry.RegisterInstance(myService);
For multiple instances you could use a factory instead.
public class MyServiceFactory
{
private readonly AppDbContext appDbContext;
public MyServiceFactory(AppDbContext appDbContext)
{
this.appDbContext = appDbContext;
}
public MyService Create() => new MyService(appDbContext);
}
Register the instance of the factory:
var context = new AppDbContext(connectionString, database);
var factory = new MyServiceFactory(context);
containerRegistry.RegisterInstance(factory);
Then create your service instance:
var factory = container.Resolve<MyServiceFactory>();
var service = factory.Create();

show Method name expected when using StructureMap

i using StructureMap in my project for using DepencyInjection . I have 5 project in my solution.
I have IUnitOfWork interface in DAL and I Defnation Function of IUnitOfWork in ApplicationDbContext .
ApplicationDbContext :
public class ApplicationDbContext : DbContext, IUnitOfWork
{
public ApplicationDbContext()
: base("ApplicationDBContext")
{
}
public virtual DbSet<User> Users { get; set; }
public void ForceDatabaseInitialize()
{
Database.Initialize(true);
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
#region IUnitOfWork Members
public void MarkAsDeleted<TEntity>(TEntity entity) where TEntity : class
{
Entry(entity).State = EntityState.Deleted;
}
public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
{
return base.Set<TEntity>();
}
.
.
.
now when I want to register IUnitOfWork in main project :
public static class StructureMapDefnation
{
private static readonly Lazy<Container> _containerBuilder =
new Lazy<Container>(defaultContainer, LazyThreadSafetyMode.ExecutionAndPublication);
public static IContainer Container
{
get { return _containerBuilder.Value; }
}
private static Container defaultContainer()
{
var container = new Container(ioc =>
{
// map same interface to different concrete classes
ioc.For<IUser>().Use<EfUserService>();
ioc.For<IUnitOfWork>().Use(() => new ApplicationDbContext())();
});
container.AssertConfigurationIsValid();
return container;
}
}
it show me this error :
Severity Code Description Project File Line Suppression State
Error CS0149 Method name expected BimehKosarFinal E:\myproject\BimehKosarFinal\BimehKosarFinal\StructureMap\StructureMapDefnation.cs 28 Active
in this line :
ioc.For<IUnitOfWork>().Use(() => new ApplicationDbContext())();
whats the problem ? how can I solve this problem ?
remove the last (), and write
ioc.For<IUnitOfWork>().Use(() => new ApplicationDbContext());
Or
ioc.For<IUnitOfWork>().Use<ApplicationDbContext>();

Call different methods, from different repositories, in same transaction using Unit of work

I am still learning UnitOfWork pattern and I am not comfortable with this yet. I found many examples but nothing is clear enough for my problem.
I want use UnitOfWork with Ado.Net.
I have many repositories. I want call different methods from different repositories in same transaction using Unit of work.
For example a have this 2 repositories.
public class FirstRepository : IFirstRepository
{
private readonly ILogger logger;
private readonly IImportConfiguration configuration;
public FirstRepository(ILogger logger, IImportConfiguration configuration)
{
this.logger = logger;
this.configuration = configuration;
}
public int Save()
{
//Save to DB with Ado.Net
return 1;
}
}
public class SecondRepository : ISecondRepository
{
private readonly ILogger logger;
private readonly IImportConfiguration configuration;
public SecondRepository(ILogger logger, IImportConfiguration configuration)
{
this.logger = logger;
this.configuration = configuration;
}
public int Update()
{
//Update in DB with Ado.Net
return 1;
}
}
I want call functions Save() and Update() in same transaction.
using (var uow = UnitOfWorkFactory.Create())
{
firstRepository.Save();
secondRepository.Update();
_unitOfWork.SaveChanges();
}
Problem is how to use same UnitOfWork in both repositories ? Only thing I can see is add additional parameter to functions
//in first repository
Save(IUnitOfWork uow)
//in second repository
Update(IUnitOfWork uow)
//****************************
using (var uow = UnitOfWorkFactory.Create())
{
firstRepository.Save(uow);
secondRepository.Update(uow);
_unitOfWork.SaveChanges();
}
This is ugly solution, because i must have this parameter in all functions that work with DB.
I am using Dependency injection. ILogger and IImportConfiguration are injected with AutoFac. Maybe would be good to register all repositories in UnitOfWork? But how to do that? I cant have just one instance injected in all repositories.
Any idea?
public class UnitOfWork
{
public DbSet<Company> Companies { get; set; }
public int SaveChanges()
{
underlyingContext.SaveChanges();
}
}
public class UnitOfWorkFactory
{
public UnitOfWork Create()
{
// real creation logic
return new UnitOfWork();
}
}
public class CompanyRepository
{
private readonly UnitOfWork uow;
public CompanyRepository(UnitOfWork uow)
{
uow = uow;
}
public void Add(Company company)
{
uow.Companies.Add(company);
}
}
public class CompanyRepositoryFactory
{
public Create(UnitOfWork uow)
{
new CompanyRepository(uow);
}
}
Tying it all together:
var uow = new UnitOfWorkFactory().Create();
var companyRepository = new CompanyRepositoryFactory().Create(uow);
So to use DI, you need to create interfaces for all these.
The unit of work is based round some Data Layer connection, for example EF uses DbContext which you would use in the underlying UnitOfWork class.
Other things you can do is make IUnitOfWork (the interface) inherit IDisposable so you use the using().
To make it so you don't have a hundred repository classes (although not really a bad thing) you can make it Generic, so IRepository<T> and Repository<T>
So for a generic repo and unit of work using EF.
public class UnitOfWork : IUnitOfWork
{
ProjectDbContext context;
public UnitOfWork() {
context = new ProjectDbContext();
}
public IQueryable<T> Query<T>(Expression<Func<bool, t>> predicate)
{
return context.Set<T>().Where(predicate);
}
public void Add<T>(T entity)
{
context.Set<T>().Add(entity);
}
public int SaveChanges()
{
return context.SaveChanges();
}
public void Dispose()
{
context.Dispose();
}
}
public class UnitOfWorkFactory
{
Lazy<UnitOfWork> lazyUOW = new Lazy<UnitOfWork>(() => new UnitOfWork());
public UnitOfWork Create()
{
// having the DI initialise as Singleton isn't enough.
return lazyUOW.Value;
}
}
public class Repository<T> : IRepository<T>
{
private readonly IUnitOfWork uow;
public Repository(IUnitOfWork uow)
{
uow = uow;
}
public void Add(T entity)
{
uow.Add(entity);
}
public List<T> AllBySomePredicate(Expression<Func<bool, T>> predicate)
{
return uow.Query(predicate).ToList();
}
}
public class RepositoryFactory : IRepositoryFactory
{
public Create<T>(UnitOfWork uow)
{
new Repistory<T>(uow);
}
}
Usage:
public class CompanyController : Controller
{
private readonly IUnitOfWorkFactory uowFactory;
private readonly IRepositoryFactory repoFactory;
public CompanyController (
IUnitOfWorkFactory uowFactory,
IRepositoryFactory repoFactory)
{
uowFactory = uowFactory;
repoFactory = repoFactory;
}
public ActionResult Index()
{
using(var uow = uowFactory.Create())
{
var companyRepo = repoFactory.Create<Company>(uow);
return View(companyRepo.AllBySomePredicate(x => x.CompanyJoined == DateTime.Now.AddMonths(-2)));
}
}
}

Categories

Resources