解决Autofac中Http请求之外的Http Request Scoped实例

时间:2010-06-10 00:17:04

标签: ioc-container autofac

假设我有一个注册为HttpRequestScoped的依赖项,因此每个请求只有一个实例。我怎么能在HttpRequest之外解析相同类型的依赖?

例如:

// Global.asax.cs Registration
builder.Register(c => new MyDataContext(connString)).As<IDatabase>().HttpRequestScoped();
_containerProvider = new ContainerProvider(builder.Build());

// This event handler gets fired outside of a request
// when a cached item is removed from the cache.
public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r)
{
    // I'm trying to resolve like so, but this doesn't work...
    var dataContext = _containerProvider.ApplicationContainer.Resolve<IDatabase>();
    // Do stuff with data context.
}

上面的代码在执行CacheItemRemoved处理程序时抛出DependencyResolutionException:

  

没有匹配表达式'value的范围(Autofac.Builder.RegistrationBuilder`3 +&lt;&gt; c__DisplayClass0 [MyApp.Core.Data.MyDataContext,Autofac.Builder.SimpleActivatorData,Autofac.Builder.SingleRegistrationStyle])。lifetimeScopeTag.Equals (scope.Tag)'在请求实例的范围内可见。

1 个答案:

答案 0 :(得分:3)

InstancePerLifetimeScope(),而非HttpRequestScoped(),将提供您需要的结果。

但有一点需要注意 - 如果IDatabase需要处理,或者取决于需要处理的内容,如果从ApplicationContainer解决它,则不会发生这种情况。更好:

using (var cacheRemovalScope =
        _containerProvider.ApplicationContainer.BeginLifetimeScope())
{
    var dataContext = cacheRemovalScope.Resolve<IDatabase>();
    // Do what y' gotta do...
}