对于 cmets,最不“架构”痛苦的方法可能是创建自己的 Scoped<T> 类,该类将解析当前 HttpContext 中的 DbContext
// Use an interface, so we don't have infrastructure dependencies in our domain
public interface IScoped<T> where T : class
{
T Instance { get; }
}
// Register as singleton too.
public sealed class Scoped<T> : IScoped<T> where T : class
{
private readonly IHttpContextAccessor contextAccessor;
private HttpContext HttpContext { get; } => contextAccessor.HttpContext;
public T Instance { get; } => HttpContext.RequestServices.GetService<T>();
public Scoped(IHttpContextAccessor contextAccessor)
{
this.contextAccessor = contextAccessor ?? throw new ArgumentNullException(nameof(contextAccessor));
}
}
注册为
// Microsoft.Extensions.DependencyInjection
services.AddSingleton(typeof(IScoped<>), typeof(Scoped<>);
// Autofac
containerBuilder.RegisterType(typeof(Scoped<>))
.As(typeof(IScoped<>));
然后将其注入您的验证器服务。
public class CustomerValidator: AbstractValidator<Customer>
{
private readonly IScoped<AppDbContext> scopedContext;
protected AppDbContext DbContext { get } => scopedContext.Instance;
public CustomValidator(IScoped<AppDbContext> scopedContext)
{
this.scopedContext = scopedContext ?? throw new ArgumentNullException(nameof(scopedContext));
// Access DbContext via this.DbContext
}
}
通过这种方式,您可以注入任何范围内的服务,而无需进一步注册。
补充说明
Autofac 被认为是“conformer”(请参阅docs)DI 并与 ASP.NET Core 和 Microsoft.Extensions.DependencyInjection 很好地集成。
来自文档
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add services to the collection.
services.AddMvc();
// Create the container builder.
var builder = new ContainerBuilder();
// Register dependencies, populate the services from
// the collection, and build the container. If you want
// to dispose of the container at the end of the app,
// be sure to keep a reference to it as a property or field.
builder.RegisterType<MyType>().As<IMyType>();
builder.Populate(services);
this.ApplicationContainer = builder.Build();
// Create the IServiceProvider based on the container.
return new AutofacServiceProvider(this.ApplicationContainer);
}
Startup 类和 Microsoft.Extensions.DependencyInjection 容器的默认用法存在一些细微差别。
-
ConfigureServices 不再是 void,它返回 IServiceProvider。这将告诉 ASP.NET Core 使用返回的提供程序,而不是来自 Microsoft.Extensions.DependencyInjection 的 DefaultServiceProvider。
- 我们返回 Autofac 容器适配器:
new AutofacServiceProvider(this.ApplicationContainer),它是根容器。
这对于让 ASP.NET Core 在 ASP.NET Core 中的任何地方都使用容器非常重要,即使在通过 HttpContext.RequestedServices 解析每个请求依赖关系的中间件内部也是如此。
因此,您不能在 Autofac 中使用 .InstancePerRequest() 生命周期,因为 Autofac 无法控制创建范围,只有 ASP.NET Core 可以做到。所以没有简单的方法让 ASP.NET Core 使用 Autofac 自己的请求生命周期。
相反,ASP.NET Core 将创建一个新范围(使用 IServiceScopeFactory.CreateScope())并使用 Autofac 的范围容器来解决每个请求的依赖关系。