ASP.NET 每个请求 5 (VNext) 个 Autofac 实例

ASP.NET 5 (VNext) Autofac Instance per Request

我正在玩 ASP.NET vNext,我想利用 InstancePerRequest 进行一些注册,例如 MyDbContext 就是一个例子。

我已经 Autofac 运行 使用 InstancePerLifetimeScope 作为这些依赖项。哪个有效....

但是当我改用 InstancePerRequest 时,我得到了这个常见错误:

DependencyResolutionException: No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.

我已经阅读了有关此问题的 Autofac 帮助文档....但我不确定如何设置导致此异常的 "request lifetime scope"。

有没有人设置 ASP.NET 5 网络应用程序集成 Autofac,包括 InstancePerRequest

据我所知,您有两种选择,它们都会根据请求为您提供实例。

假设您有以下 class 注册:

public class Foo : IDisposable 
{
    public Foo()
    {
        Console.WriteLine("created");
    }

    public void Dispose()
    {
        Console.WriteLine("disposed");
    }
}

向 IServiceCollection 注册

您可以将实例注册为 IServiceCollection 范围内的实例,并基于此构建 Autofac 容器。

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddScoped<Foo, Foo>();

#if DNX451
            // Create the autofac container
            var builder = new ContainerBuilder();

            // Create the container and use the default application services as a fallback
            AutofacRegistration.Populate(builder, services);
            var container = builder.Build();

            return container.Resolve<IServiceProvider>();
#endif

            return services.BuildServiceProvider();
        }

在 Autofac Builder 上注册

您可以在 Autofac 构建器上将类型注册为每个生命周期范围的实例,这将为您提供每个请求生命周期的实例:

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
#if DNX451

            // Create the autofac container
            var builder = new ContainerBuilder();

            // Create the container and use the default application services as a fallback
            AutofacRegistration.Populate(builder, services);
            builder.RegisterType<Foo>().As<Foo>().InstancePerLifetimeScope();
            var container = builder.Build();

            return container.Resolve<IServiceProvider>();
#endif

            return services.BuildServiceProvider();
        }

如上所述,两者的结果相同:

有关 ASP.NET 5 上每个请求实例的更多信息:Middlewares and Per Request Dependency Injection