获取数据访问层内的数据库上下文

2024-02-04

我在尝试解决 EF-Core 方面的一些问题。
我使用 MVC Core 应用程序中的启动代码来初始化数据库上下文。
这是我的数据库上下文:

public class AccountsDBContext : DbContext
{
    public AccountsDBContext(DbContextOptions<AccountsDBContext> options)
        :base(options)
    {

    }

    // ...

}

以及启动代码:

 public void ConfigureServices(IServiceCollection services)
 {
        // Inject the account db
        services.AddDbContext<AccountsDBContext>(options =>
           options.UseMySQL(Configuration.GetConnectionString("AccountsStore")));

        // ...

在所有示例中,我看到数据库上下文是通过构造函数传递到控制器(我假设通过依赖项注入)并从那里传递到其他实体\层。

 [Route("api/[controller]")]
 public class AccountsController : Controller
 {
    private AccountsDBContext _db;

    public AccountsController(AccountsDBContext context)
    {
        this._db = context;
    }

但是,我不太喜欢数据库上下文将成为控制器成员的想法。
我真的更喜欢在数据访问层中获取数据库上下文,而不是将其传递到存储库类中。
有没有办法获取数据访问层内的上下文?(据我所知,那里没有 IServiceCollection、IApplicationBuilder、IServiceScopeFactory)


我明白你想做什么。我正是这样做的。关键是在 DAL 中创建一个使用 IServiceCollection 的静态类。然后在这里你添加你的上下文这是我的,它很有效我的前端甚至不知道实体框架,下面是我的业务层:

public static IServiceCollection RegisterRepositoryServices(this IServiceCollection services)
    {
        services.AddIdentity<ApplicationUser, IdentityRole<int>>(
            config => { config.User.RequireUniqueEmail = true;
                config.Cookies.ApplicationCookie.LoginPath = "/Account/Login";
                config.Cookies.ApplicationCookie.AuthenticationScheme = "Cookie";
                config.Cookies.ApplicationCookie.AutomaticAuthenticate = false;
                config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
                {
                    OnRedirectToLogin = async ctx =>
                    {
                        if (ctx.Request.Path.StartsWithSegments("/visualjobs") && ctx.Response.StatusCode == 200)
                        {
                            ctx.Response.StatusCode = 401;
                        }
                        else
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                        await Task.Yield();
                    }
                };
            }).AddEntityFrameworkStores<VisualJobsDbContext, int>()
          .AddDefaultTokenProviders();

        services.AddEntityFramework().AddDbContext<VisualJobsDbContext>();

        services.AddScoped<IRecruiterRepository, RecruiterRepository>();
        services.AddSingleton<IAccountRepository, AccountRepository>();

        return services;
    }

然后在我的服务层中我有另一个静态类。我的服务层引用了存储库层,我在这里注册存储库服务(将存储库引导到服务层),就像这样,然后我在 UI 中再次执行相同的操作:

服务层代码:

public static class ServiceCollectionExtensions
{
    public static IServiceCollection RegisterServices(this IServiceCollection services)
    {
        services.RegisterRepositoryServices();
        services.AddScoped<IRecruiterService, RecruiterService>();
        services.AddSingleton<IAccountService, AccountService>();

        return services;
    }
}

存储库层的魔力:

public partial class VisualJobsDbContext : IdentityDbContext<ApplicationUser, IdentityRole<int>, int>
{
    private IConfigurationRoot _config;

    public VisualJobsDbContext() { }

    public VisualJobsDbContext(IConfigurationRoot config, DbContextOptions<VisualJobsDbContext> options) : base(options)
    {
        _config = config;
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);

        optionsBuilder.UseSqlServer(@_config["ConnectionStrings:VisualJobsContextConnection"]);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {....
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取数据访问层内的数据库上下文 的相关文章

随机推荐

  • Android MapActivity:无法获取连接工厂客户端

    我正在尝试让地图演示正常工作 如 Google API 中提供的那样 示例项目 我正在使用 AVD 并尝试过版本 8 10 和 11 并得到同样的问题 我已经生成了自己的调试密钥并添加到项目中 我可以看到 应用程序上的地图启动 并且可以放大
  • 如何在 Android Studio Logcat 中突出显示过滤器/搜索命中

    我根据单个字符串过滤 Logcat 行 如下所示 但在那里 我面临着许多很长的队伍 而且我很难识别队伍中间想要的值 例如 在上图中 看到所有 聚合 关键字突出显示会非常方便 有没有办法在 Logcat 控制台上突出显示过滤 搜索命中 据我所
  • 禁用的按钮在 Firefox 和 Chrome 中看起来已启用

    禁用的按钮在 Firefox 和 Chrome 中看起来已启用 我在 ie firefox chrome 中打开同一页面 这是输出 仪表板 和 日历 被禁用 代理信息 已启用 这里我使用带有 css 的普通 asp 按钮 我该怎么办 您可以
  • 替换标签并保留属性[重复]

    这个问题在这里已经有答案了 可能的重复 更改标签名称但保留所有属性 https stackoverflow com questions 6482847 change the tag name but keep all the attribu
  • Javascript - 从数组中删除唯一元素

    我想知道如何从数组中删除唯一元素 例如 var arr 1 2 2 4 4 会回来 2 2 4 4 Where 1 2 3 会回来 因为所有元素都是独一无二的 我相信我需要将每个元素与数组中的每个其他元素进行检查 但我不确定如何进行此操作
  • 数据结构成员的成员初始化

    我刚刚遇到了一个尴尬的问题 这个问题很容易解决 但我不喜欢这样做 在我的类的构造函数中 我正在初始化数据成员的数据成员 这是一些代码 class Button private The attributes of the button SDL
  • 如何使用Mono的“缓存”方法

    我是 spring webflux 的初学者 在研究时我发现了一些代码 例如 Mono result someMethodThatReturnMono cache 缓存 这个名字告诉我关于缓存某些东西 但是缓存在哪里以及如何检索缓存的东西
  • android 从 JavascriptInterface 启动Activity

    简单的一般问题 Webview 连接到我的 JavascriptInterface 类 并且它肯定是有用的 但是 因为 JavascriptInterface 不扩展 Activity 所以我似乎无法使用 startActivity int
  • 锦标赛分组放置算法

    给定对手种子列表 例如种子 1 到 16 我正在尝试编写一种算法 该算法将导致头号种子在该轮中对阵最低的种子 第二名种子对阵第二低的种子 依此类推 将 1 和 16 2 和 15 等分组为 比赛 相当容易 但我还需要确保较高的种子将在后续回
  • 使用C#或Powershell扫描所有可用的无线网络并连接到特定的SSID

    我正在尝试编写一个脚本来扫描所有可用的无线网络并连接到特定网络 SSID 有人已经为此编写了示例代码吗 由于某些限制 我无法安装第三方软件 托管 wifi api 查看这篇相关文章 在 C 中管理无线网络连接 https stackover
  • 未捕获的类型错误:无法解析模块说明符“firebase/app”。相对引用必须以“/”、“./”或“../”开头

    我遵循了有关 WebRTC 视频聊天的 YouTube 教程 因此我尝试编写它 在 localhost 中它可以工作 但是当我将其上传到 firebase 托管时 它就会出现此错误 我能做些什么 我是网络开发新手 所以请耐心等待 主要 ht
  • 如何从字符串中删除0

    我正在看函数trim但不幸的是 这并没有删除 0 我该如何将其添加到其中 我应该使用str replace 编辑 我要修改的字符串是一个消息编号 如下所示 00023460 功能ltrim 00023460 0 正是我需要的 显然我不想使用
  • 在 Python 中模拟导入模块

    我正在尝试对使用导入的外部对象的函数实施单元测试 例如助手 py is import os import pylons def some func arg var1 os path exist var2 os path getmtime v
  • 无法使用 OpenCV 从辅助网络摄像头的 VideoCapture 读取帧

    Code 与主网络摄像头 设备 0 完美配合的简单示例 VideoCapture cap 0 if cap isOpened std cout lt lt Unable to read stream from specified devic
  • 为什么我在 raw_input 期间无法捕获 KeyboardInterrupt?

    这是一个测试用例 try targ raw input Please enter target except KeyboardInterrupt print Cancelled print targ 当我按 ctrl c 时 我的输出如下
  • SqlAlchemy - 按关系属性过滤

    我对 SQLAlchemy 没有太多经验 但我遇到了一个无法解决的问题 我尝试搜索并尝试了很多代码 这是我的课程 简化为最重要的代码 class Patient Base tablename patients id Column Integ
  • 在 Bolts 中,如何使用 continueWith() 和 continueWithTask()?

    除了同步与异步之外 它们文档中的差异也让我感到困惑 他们的例子github页面 https github com BoltsFramework Bolts Android chaining tasks together看起来仍然是同步调用的
  • Netbeans - 从数据库生成实体类

    我使用的是 netbeans IDE 7 1 我正在尝试从数据库 sql server 生成实体类 我能够设置与此远程数据源的连接 但在数据库向导的新实体类中 表没有显示 并且在底部显示 选择至少一个表 我可以执行查询并浏览 netbean
  • 如何在Altera Quartus中生成.rbf文件?

    什么是 rbf 文件以及如何在 Windows 上从 Quartus 输出文件 sof 生成它们 An RBF is a 原始二进制文件例如 它代表原始数据 这些数据将被加载到闪存中 以便在上电时初始化 FPGA A SOF is an S
  • 获取数据访问层内的数据库上下文

    我在尝试解决 EF Core 方面的一些问题 我使用 MVC Core 应用程序中的启动代码来初始化数据库上下文 这是我的数据库上下文 public class AccountsDBContext DbContext public Acco