本文介绍了Autofac寿命和匹配终身范围内默认提供的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Autofac依赖注入一个ASP.NET MVC的Web应用程序。偶尔,这个Web应用程序将启动一个线程做一些工作,从请求的线程是分开的。当这个后台线程启动时,它建立从根容器的新Autofac一生范围和运行一些行动。

I have an ASP.NET MVC web application using Autofac for dependency injection. Occasionally, this web application will start a thread to do some work separate from the request thread. When this background thread starts up, it establishes a new Autofac lifetime scope from the root container and runs some action.

public IAsyncResult Run<T>(Action<T> action)
{
    var NewTask = System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
        using (var Scope = Runtime.Container.BeginLifetimeScope())
        {
            var Input = Scope.Resolve<T>();
            action(Input);
        }
    });

    return NewTask;
}



我的一个与Autofac注册的依赖有两种不同的实现方式:一种适用于HTTP -request寿命和另一个适用于所有其他的寿命。我试图把它们注册为如下:

One of my dependencies registered with Autofac has two different implementations: one appropriate for http-request lifetimes and another appropriate for all other lifetimes. I tried to register them as follows:

builder
.Register(c => new Foo())
.As<IFoo>()
.InstancePerLifetimeScope();

builder
.Register(c => new FooForHttp(HttpContext.Current))
.As<IFoo>()
.InstancePerMatchingLifetimeScope(WebLifetime.Request);



Autofac选择 FooForHttp HTTP请求(如预期)。然而,当我的后台线程旋转起来,任何试图解决的IFoo 导致异常:

Autofac selects FooForHttp for http requests (as expected). However, when my background thread spins up, any attempt to resolve IFoo results in an exception:

没有一个标签匹配的HttpRequest'的范围是其中要求该实例的范围
可见。这通常表示登记为每个HTTP请求一个
成分是由一个
SingleInstance()成分reqested(或类似的情形。)在卷筒纸
积分总是请求依赖从
DependencyResolver.Current或ILifetimeScopeProvider.RequestLifetime,
永远不会从容器本身。

我知道Autofac总是使用最后的注册供应商为特定组件的默认提供商。我在这里做一个假设,它会使用最后一个登记的适用的人员。

I know that Autofac always uses the last registered provider as the default provider for a particular component. I made an assumption here that it would use the last registered suitable provider.

我缺少的东西,或者是有没有选择一个更好的方法基于当前的寿命范围内的标签供应商?

Am I missing something, or is there a better approach to selecting a provider based on the tag of the current lifetime scope?

推荐答案

注册网页富正常,但不注册其他富。当创建异步任务的寿命范围,使用BeginLifetimeScope(那发生在ContainerBuilder一个动作过载)。注册背景美孚在这个动作(B => b.Register()),这应该重写网页之一。 (小键盘不好意思在这里:))

Register the web Foo as normal, but don't register the other Foo. When creating the lifetime scope for the async task, use the overload of BeginLifetimeScope() that takes an action on ContainerBuilder. Register the background Foo in this action (b => b.Register()) and this should override the web one. (Small keyboard here sorry :))

这篇关于Autofac寿命和匹配终身范围内默认提供的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 09:38