AutoFac/.NET Core - 注册DBcontext

Kyl*_*nes 16 c# autofac .net-core ef-core-2.0

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

API - >业务/域 - >基础架构

只有API方法,API非常薄.业务/域层具有我的所有业务逻辑.最后,我的Infrastructure层使用EF Core 2.0创建了我的DB类.

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

services.AddDbContext<MyContext>(options => options.UseSqlServer(connectionString));
Run Code Online (Sandbox Code Playgroud)

但是,我想保持更传统的关注点分离.到目前为止,我在我的Infrastructure层添加了一个模块,试图进行如下注册:

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();
Run Code Online (Sandbox Code Playgroud)

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

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

Ale*_*man 12

我使用Autofac来注册HttpContextAccessorDbContext.

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

builder
    .RegisterType<AppDbContext>()
    .WithParameter("options", DbContextOptionsFactory.Get())
    .InstancePerLifetimeScope();
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

DbContextConfigurer

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


Ale*_*nov 8

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

  • 你是对的.我改变了.AsImplementedInterfaces()到.AsSelf(),现在它正在工作.谢谢! (2认同)

小智 7

Autofac 4.8.1 版的另一个简单解决方案

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().AddControllersAsServices();

        services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionStrings:MyConnection:ConnectionString")));

        var builder = new ContainerBuilder();

        builder.Populate(services);

        //...
        // Your interface registration
        //...

        builder.Build(Autofac.Builder.ContainerBuildOptions.None);
    }
Run Code Online (Sandbox Code Playgroud)


rda*_*ins 5

这是我使用的一个实现 - 它模仿EF Core 3.1 注册到 Autofac 4.9.4。请务必根据您的要求调整范围。

public void RegisterContext<TContext>(ContainerBuilder builder)
    where TContext : DbContext
{
    builder.Register(componentContext =>
        {
            var serviceProvider = componentContext.Resolve<IServiceProvider>();
            var configuration = componentContext.Resolve<IConfiguration>();
            var dbContextOptions = new DbContextOptions<TContext>(new Dictionary<Type, IDbContextOptionsExtension>());
            var optionsBuilder = new DbContextOptionsBuilder<TContext>(dbContextOptions)
                .UseApplicationServiceProvider(serviceProvider)
                .UseSqlServer(configuration.GetConnectionString("MyConnectionString"),
                    serverOptions => serverOptions.EnableRetryOnFailure(5, TimeSpan.FromSeconds(30), null));

            return optionsBuilder.Options;
        }).As<DbContextOptions<TContext>>()
        .InstancePerLifetimeScope();

    builder.Register(context => context.Resolve<DbContextOptions<TContext>>())
        .As<DbContextOptions>()
        .InstancePerLifetimeScope();

    builder.RegisterType<TContext>()
        .AsSelf()
        .InstancePerLifetimeScope();
}
Run Code Online (Sandbox Code Playgroud)