.NET Core Web API中使用Autofac注册DbContext的方法咨询
Hey there! Let's walk through exactly how to register your EF Core 2.0 DbContext using Autofac in your layered .NET Core Web API project. I'll break this down into clear, actionable steps that fit your existing architecture (API → Business/Domain → Infrastructure).
Step 1: Install Required NuGet Packages
First, make sure you have these packages installed in your API project (and any dependent projects if needed):
Autofac.Extensions.DependencyInjection: Integrates Autofac with .NET Core's hosting systemAutofac.Extras.EntityFrameworkCore: Provides helper methods to simplify EF Core DbContext registration with Autofac- You should already have
Microsoft.EntityFrameworkCoreand the appropriate provider (likeMicrosoft.EntityFrameworkCore.SqlServer) in your Infrastructure project.
Step 2: Configure Autofac as the Service Provider
In your Program.cs, update the BuildWebHost method to tell .NET Core to use Autofac instead of the default DI container:
public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseServiceProviderFactory(new AutofacServiceProviderFactory()) // Enable Autofac .Build();
Step 3: Set Up Autofac Container Configuration in Startup.cs
Next, add a ConfigureContainer method to your Startup class—this is where you'll define all your Autofac registrations, including the DbContext. You can keep your existing ConfigureServices method for any built-in .NET Core services (like MVC), but we'll handle DbContext and layered services in Autofac's configuration.
Here's a complete example of how this looks:
using Autofac; using Autofac.Extras.EntityFrameworkCore; using YourNamespace.Infrastructure.Data; // Your DbContext lives here using YourNamespace.Business.Services; // Your business logic services public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } // Keep this for built-in services like MVC public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // No need to register DbContext here anymore—Autofac handles it } // Autofac-specific container configuration public void ConfigureContainer(ContainerBuilder builder) { // 1. Register your DbContext with Autofac's EF helper builder.RegisterDbContext<YourDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // 2. Register all business layer services (scan the assembly) // This automatically registers all classes in your Business assembly // that implement interfaces, with a per-request lifetime builder.RegisterAssemblyTypes(typeof(YourBusinessService).Assembly) .AsImplementedInterfaces() .InstancePerLifetimeScope(); // 3. Register infrastructure layer services (e.g., repositories) builder.RegisterAssemblyTypes(typeof(YourRepository).Assembly) .AsImplementedInterfaces() .InstancePerLifetimeScope(); } // Your existing Configure method for middleware stays the same public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); } }
Key Details to Note
- DbContext Lifetime:
RegisterDbContextdefaults toInstancePerLifetimeScope, which means one DbContext instance per HTTP request—this is the recommended practice for EF Core to avoid concurrency issues and manage resources efficiently. - Assembly Scanning: Using
RegisterAssemblyTypeslets you avoid manually registering every business service or repository, which keeps your configuration clean as your project grows. Just point it to the assembly containing your services/repositories. - Autofac vs. Built-in DI: Autofac will handle all the registrations you define in
ConfigureContainer, and it integrates seamlessly with any services you registered inConfigureServices(like MVC).
Alternative: Manual DbContext Registration (If You Don't Want the Autofac EF Extension)
If you prefer not to use Autofac.Extras.EntityFrameworkCore, you can register the DbContext manually:
builder.Register(c => { var optionsBuilder = new DbContextOptionsBuilder<YourDbContext>(); optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")); return new YourDbContext(optionsBuilder.Options); }).AsSelf().InstancePerLifetimeScope();
This achieves the same result but requires a bit more code.
内容的提问来源于stack exchange,提问作者Kyle Barnes

