【发布时间】:2020-02-01 19:12:53
【问题描述】:
我来了
- .net Core 3.0 web api
- token jwt / owin
- EF Core 3
我有一个多数据库项目。用户在登录表单中从列表中选择一个数据库。之后,我在“selectedDb”声明中设置了 dbName/connectionString
在每个控制器中,我有 8 到 20 个类(管理器)需要 DbContext 作为参数构造器 => 我无法在控制器构造器中创建管理器或 dbContext 的实例,因为我还没有登录令牌!
所以,在每个动作中,我创建了一个 dbContext(令牌提供连接字符串)和管理器的 istance...但这意味着我必须在每个动作中“复制/粘贴”相同的 3/4 行代码
如何提供一个有效的数据库上下文实例?可能使用中间件或自定义授权属性
有没有办法在控制器构造函数中创建 dbcontext 的实例? (使用令牌提供的“动态连接字符串”)
一些代码示例
初始化类函数(避免每次复制16&3#92行)
private DatabaseContext InitContextAndManager(string connectionString)
{
_dbContext = new DatabaseContext(connectionString);
_someManager1 = new SomeManager_1(_dbContext);
_someManager2 = new SomeManager_2(_dbContext);
_someManager3 = new SomeManager_3(_dbContext);
_someManager4 = new SomeManager_4(_dbContext);
_someManager5 = new SomeManager_5(_dbContext);
_someManager6 = new SomeManager_6(_dbContext);
_someManager7 = new SomeManager_7(_dbContext);
_someManager8 = new SomeManager_8(_dbContext);
_someManager9 = new SomeManager_9(_dbContext);
_someManager10 = new SomeManager_10(_dbContext);
_someManager11 = new SomeManager_11(_dbContext);
_someManager12 = new SomeManager_12(_dbContext);
_someManager13 = new SomeManager_13(_dbContext);
_someManager14 = new SomeManager_14(_dbContext);
_someManager15 = new SomeManager_15(_dbContext);
}
一些 API 示例
[Authorize]
public ActionResult Api_1()
{
var connectionString = User.Identity.GetConnectionString();
InitContextAndManager(connectionString);
//some api_1 stuff
}
[Authorize]
public ActionResult Api_2()
{
var connectionString = User.Identity.GetConnectionString();
InitContextAndManager(connectionString);
//some api_2 stuff
}
[Authorize]
public ActionResult Api_3()
{
var connectionString = User.Identity.GetConnectionString();
InitContextAndManager(connectionString);
//some api_3 stuff
}
【问题讨论】:
-
看看我的回答here。在 DbConnectionInfo 中,您可以访问声明并设置连接字符串。
-
对不起,我不明白你的意思@RuardvanElburg
-
@RuardvanElburg 添加了详细信息
-
ASP.NET Core 支持依赖注入 (DI) 软件设计模式,这是一种在类及其依赖项之间实现控制反转 (IoC) 的技术。 documentation。在该模式中,您不会创建对象(new 关键字)而是注入它们。我的答案是基于 DI。
标签: c# asp.net .net-core middleware jwt-auth