1

I am new to the ASP.NET WebAPI project and building the new project with the following structure :-

Project.MainAPIService
Project.BusinessManager
Project.Model
Project.Repository
Project.Common

I am using Autofac to perform the DI in the whole project. And the flow is like this :-

API controller   >>>>>> (DI) Business Manager >>>> (DI) Repository & creates the DBContext object manually.

My Repository class is looking like this. And now i want to pass the client-name dynamically into the Repository class, so that it makes the DB connection to the particular client db only. But i unable to pass the client-name from businessManager project to PDLRepository and further down to DBContext class.

public class MyRepository : IMyRepository, IDisposable
    {
        myContext _context = new myContext("ClientX");

        private IGenericRepository<Mapping> _docMappingGenericRepo;
        private IGenericRepository<Document> _DocGenericRepo;
        private IGenericRepository<Activity> _activityGenericRepo;
    }

mycontext class looks like this :-

 public partial class mycontext : DbContext
    {
        public mycontext (string ClientName)
            : base(ConnectionUtil.GetConnectionString(ClientName))
        { }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.SetInitializer<myContext>(null);
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }

        public virtual DbSet<DocumentMapping> DocumentMapping { get; set; }

        public virtual DbSet<Document> Document { get; set; }
   }

Please suggest your views how to fix the myContext or MyRepository class accordingly. How will i pass the client-name from BusinessManager to Repository to DBContext class ?

Please help me out here.

Karan
  • 3,265
  • 9
  • 54
  • 82

1 Answers1

0

Do not create myContext in Repository. Remove following line from Repository.

myContext _context = new myContext("ClientX");

Instead, create and manage myContext in BusinessManager. As BusinessManager already know ClientName, it can be created there without trouble with the same line we removed from Repository.

Now, inject myContext in Repository.

You apparently have multiple databases; one per client. So one database represent one client. Connection represents Database and myContext is handling Connection. So, approach I mentioned above makes more sense.

Repository executes the action, it should not control Connection. Using this approach, you can also include multiple Repositories in one myContext which will help you cover all those repositories under one transaction/UoW.

This answer explains how to do this with Dapper. Technology may not be related to you; but rest of the details may help you.

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141