在 Autofac 中解析 HttpRequest 之外的 HttpRequestScoped 实例
假设我有一个注册为 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:
没有范围与表达式“值(Autofac.Builder.RegistrationBuilder`3+<>c__DisplayClass0[MyApp.Core.Data.MyDataContext,Autofac.Builder.SimpleActivatorData,Autofac.Builder.SingleRegistrationStyle]).lifetimeScopeTag.Equals匹配(scope.Tag)' 在请求实例的范围内可见。
Suppose I have a dependency that is registered as HttpRequestScoped so there is only one instance per request. How could I resolve a dependency of the same type outside of an HttpRequest?
For example:
// 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.
}
The above code throws a DependencyResolutionException when it executes the CacheItemRemoved handler:
No scope matching the expression 'value(Autofac.Builder.RegistrationBuilder`3+<>c__DisplayClass0[MyApp.Core.Data.MyDataContext,Autofac.Builder.SimpleActivatorData,Autofac.Builder.SingleRegistrationStyle]).lifetimeScopeTag.Equals(scope.Tag)' is visible from the scope in which the instance was requested.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
InstancePerLifetimeScope()
,而不是HttpRequestScoped()
,将给出您需要的结果。但有一个警告 - 如果 IDatabase 需要处置,或者依赖于需要处置的东西,如果您从 ApplicationContainer 解析它,则不会发生这种情况。最好这样做:
InstancePerLifetimeScope()
, rather thanHttpRequestScoped()
, will give the result you need.There is a caveat though - if
IDatabase
requires disposal, or depends on something that requires disposal, this won't happen if you resolve it from the ApplicationContainer. Better to do: