c# - AutoFac/.NET Core - 注册 DBcontext

标签 c# .net-core autofac ef-core-2.0

我有一个新的 .NET Core Web API 项目,它具有以下项目结构:

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

API 非常精简,只有 API 方法。业务/领域层具有我所有的业务逻辑。最后,我的基础架构层具有使用 EF Core 2.0 的数据库类。

我知道使用 .NET Core 内置的依赖注入(inject),我可以将 API 项目的引用添加到基础设施项目,然后在 StartUp.cs 文件中添加以下代码:

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

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

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 没有被注册。任何试图访问注入(inject)的 DBContext 的类都无法解析该参数。

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

最佳答案

我使用 Autofac 来注册 HttpContextAccessorDbContext

builder
    .RegisterType<HttpContextAccessor>()
    .As<IHttpContextAccessor>()
    .SingleInstance();

builder
    .RegisterType<AppDbContext>()
    .WithParameter("options", DbContextOptionsFactory.Get())
    .InstancePerLifetimeScope();

DbContextOptionsFactory

public class DbContextOptionsFactory
{
    public static DbContextOptions<AppDbContext> Get()
    {
        var configuration = AppConfigurations.Get(
            WebContentDirectoryFinder.CalculateContentRootFolder());

        var builder = new DbContextOptionsBuilder<AppDbContext>();
        DbContextConfigurer.Configure(
            builder, 
            configuration.GetConnectionString(
                AppConsts.ConnectionStringName));

        return builder.Options;
    }
}

DbContextConfigurer

public class DbContextConfigurer
{
    public static void Configure(
        DbContextOptionsBuilder<AppDbContext> builder, 
        string connectionString)
    {
        builder.UseNpgsql(connectionString).UseLazyLoadingProxies();
    }
}

关于c# - AutoFac/.NET Core - 注册 DBcontext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50125132/

相关文章:

c# - asp.net core 3.1 将 autofac 与 finbuckle 集成

c# - MVC5 : Object reference not set to an instance of an object?

c# - 在java中检查.net签名时出现问题

c# - SourceSafe CRC 计算

c# - 错误 :An unknown error occurred while invoking the service metadata component. 无法生成服务引用

azure - Webjob 导致 ASP.NET core 出现性能问题

c# - InMemoryDbContext 在种子之后不会持续存在, Controller 中的集合始终为空

c# - 在不同事件中访问同一对象

c# - 如何注册开放泛型类型、封闭泛型类型并使用 autofac 装饰两者?

c# - Autofac 的混合生活方式