Allowing HttpRequestScoped instances outside of HttpRequest in Autofac

Suppose I have a dependency registered as HttpRequestScoped, so there is only one instance per request. How can I resolve a dependency of the same type outside of HttpRequest?

For instance:

// 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 the CacheItemRemoved handler is executed:

There is 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) 'can be seen from the scope in which the instance was requested.

+4
source share
1 answer

InstancePerLifetimeScope() , not HttpRequestScoped() , will give the desired result.

However, there is a caveat - if the IDatabase requires deletion or depends on what requires deletion, this will not happen if you allow it from the ApplicationContainer. Better to do:

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

Source: https://habr.com/ru/post/1312383/


All Articles