简体   繁体   中英

Multi Tenancy in ASP.NET MVC Application

In the following example, what is an efficient way to implement multitenancy with minimal redundant code? In this scenario, tenant is a student. The students' school has 2 locations and each location is required to have the data (ie, Courses) stored in a seperate database. When a student logs in, their location determines which database to pull from.

I'm using Entity Framework and Repository Pattern. Currently I have the implementation for accessing Location 1 DB. I've looked into different options to implement Location 2, such as injecting a TenantContext in the HomeController contructor, but I am stuck on how to set the correct database connection and what approach would be most efficient.

Below is the code for Location 1 only.

Example Controller

public class HomeController : Controller
{
    ICourseRepository courseRepository;

    //How to set the correct repository to use based on location?
    public HomeController(ICourseRepository courseRepository)
    {
        this.courseRepository = courseRepository;
    }

    //Register for a new class
    public ViewResult Register()
    {
        var courseList = courseRepository.AvailableCourses();
        return View(courseList);
    }
}

CourseRepository

public class CourseRepository : ICourseRepository
{
    private Location1DB context = new Location1DB();

    public List<Course> AvailableCourses()
    {
        //Get available courses from Location 1 Course Table
    }
}

Location1Model.Context.cs (This is genereated using EF DbContext Generator)

public partial class Location1DB: DbContext
{
    public Location1DB()
        : base("name=Location1DB")
    {
    }

    public DbSet<Course> Courses { get; set; }
}

Web.config

<connectionStrings>
     <add name="Location1DB" ... />
     <add name="Location2DB" ... />
</connectionStrings>

sorry I'll try to edit and provide a more complete answer when I get time tomorrow, but check this SO answer and the castle windsor container doco to get you started (also not sure what container you are using but all the major ones should have this functionality).

The thought would be to read the LocationID out of the cookie, grab the right connection string and have the container pass it as a parameter to your dbcontext.

DbContext is a partial class remember, so you could declare your own partial DbContext class, put an interface on it and pass that as a dependency into your repository.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM