AutoFac/.NET Core - 注册 DBcontext [英] AutoFac / .NET Core - Register DBcontext

查看:37
本文介绍了AutoFac/.NET Core - 注册 DBcontext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个新的 .NET Core Web API 项目,其项目结构如下:

I have a new .NET Core Web API project that has the following projects structure:

API -> 业务/领域 -> 基础设施

API -> Business / Domain -> Infrastructure

API 非常精简,只有 API 方法.业务/领域层包含我所有的业务逻辑.最后,我的基础设施层拥有使用 EF Core 2.0 的数据库类.

The API is very thin with only the API methods. The Business / Domain layer has all my business logic. And finally, my Infrastructure layer has my DB classes using EF Core 2.0.

我知道使用 .NET Core 内置依赖注入我可以从 API 项目添加一个引用到基础结构项目,然后在 StartUp.cs 文件中添加以下代码:

I know using .NET Core built-in Dependency Injection I can add a reference from the API project to the Infrastructure project, then add the following code in the StartUp.cs file:

services.AddDbContext<MyContext>(options => options.UseSqlServer(connectionString));

但是,我想保持更传统的关注点分离.到目前为止,我已经在我的基础设施层中添加了一个模块,尝试像这样进行注册:

However, I would like to maintain a more traditional separation of concerns. So far I have added a module in my Infrastructure layer that attempts to make the registration like so:

builder.Register(c =>
        {
            var config = c.Resolve<IConfiguration>();

            var opt = new DbContextOptionsBuilder<MyContext>();
            opt.UseSqlServer(config.GetSection("ConnectionStrings:MyConnection:ConnectionString").Value);

            return new MyContext(opt.Options);
        }).AsImplementedInterfaces().InstancePerLifetimeScope();

但是,DBContext 并未注册.任何尝试访问注入的 DBContext 的类都无法解析该参数.

The DBContext, however, is not getting registered. Any class that attempts to access the injected DBContext cannot resolve the parameter.

有没有办法在 .NET Core Web API 项目中使用 AuftoFac 在单独的项目中注册 DBContext?

推荐答案

我认为问题在于您正在尝试使用 AsImplementedInterfaces() 注册 MyContext()>.这不是 DbContext 通常注册的方式.您应该注册并解析类本身.

I think that the problem is that you're trying to register MyContext() using AsImplementedInterfaces(). This is not how DbContext are getting registered usually. You should register and resolve class itself.

这篇关于AutoFac/.NET Core - 注册 DBcontext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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