.NET 5更改控制器中的DbContext [英] .Net 5 change DbContext in controller

查看:86
本文介绍了.NET 5更改控制器中的DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个设计,其中我有一个主人".数据库和多个客户端"数据库.收到请求后,我将在master数据库中查找并建立与正确的客户端数据库的连接.

I have a design where I have one "master" database and multiple "client" databases. When I get a request I lookup in the master database and setup the connection to the right client database.

我现在正在尝试在.net 5中进行相同的设计,在其中我在Startups ConfigureServices()中设置masterDB:

I'm now trying to design the same in .net 5, where I setup the masterDB in StartUps ConfigureServices():

services.AddDbContext<Models.DataContext.MasterContext>(options => 
options.UseSqlServer("Name=MasterDB"));

然后,作为每个控制器方法的第一件事,我在MasterDB中进行请求查找,并找到clientDB的connectionString.

I then on the request lookup in the MasterDB as the first thing in every controllers methods and find the connectionString for the clientDB.

但是我该如何在那时设置它?

我们也建议您采取任何稍有不同的建议.

Any advice to do things slightly different are also encouraged.

推荐答案

将您的MasterContext注入服务中,该服务为您的客户端"客户端提供连接字符串查找数据库(可能带有缓存).然后在解析和配置客户端"客户端时使用它DbContext.

Inject your MasterContext into a service that provides connection string lookups for your "client" databases (probably with caching). Then use that when resolving and configuring your "client" DbContext.

类似这样的东西:

    class ClientDatabaseService
    {
        MasterDbContext db;
        IHttpContextAccessor context;

        static Dictionary<string, string> cache = null;
        public ClientDatabaseService(MasterDbContext db, IHttpContextAccessor context)
        {
            this.db = db;
            this.context = context;
            if (cache == null) RefreshCache();
        }
        public void RefreshCache()
        {
            cache = db.Clients.Select(c => new { c.ClientID, c.ConnectionString }).ToDictionary(c => c.ClientID, c => c.ConnectionString);
        }
        public string GetClientConnectionString()
        {
            var clientId = context.HttpContext.User.FindFirst("ClientID").Value;
            
            return cache[clientId];
        }

    }
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddDbContext<MasterDbContext>();
        services.AddHttpContextAccessor();
        services.AddScoped<ClientDatabaseService>();

        services.AddDbContext<ClientDbContext>((services, options) =>
        {
            var constrService = services.GetRequiredService<ClientDatabaseService>();
            var constr = constrService.GetClientConnectionString();
            options.UseSqlServer(constr, o => o.UseRelationalNulls());

        });


    }

这篇关于.NET 5更改控制器中的DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆