Search code examples
autofac

Autofac IServiceScopeFactory changes in v8.0.0.0


I have an application which uses AutoFac + Autofac.Extensions.DependencyInjection which was working fine until upgrading A.E.DI to v8.0.0.0. Looking at the release notes its pretty clear why given at various points in the app, explicate scopes are created for units of work and the changes made in v8 mean these scopes are no longer hierarchal.

The problem specifically is some of my services are registered as having an instance per a named scope with InstancePerMatchingLifetimeScope. When a service is activated from a new scope created explicitly from the named scope, any attempts to resolve services registered as belonging to that named scope now fail - thus kind of defeating the whole point of named scopes.

I realise of course that named scopes are an AutoFac thing and as such, it would be better to not be using IServiceProvider in the first place and just use native Autofac constructs to create the units of work, but this also causes me issue as there are a couple of components which the application uses that I have no control over and they (wrongly, I know) require an explicate IServiceProvider instance. Because of this I have always adopted the approach of using the MS APIs throughout.

Is there any way of working round this change while still keeping ones application using the MS IServiceScope/IServiceProvider interfaces or is the only way to fully embrace Autofac APIs?


Solution

  • The only way to get a named scope or to get hierarchical scopes (create a child of that named scope) is to use Autofac APIs. That is the unfortunate state of things, and a choice that was implicitly made by the ASP.NET Core team. You can follow the long chain of discussions here. We (Autofac folks) had no idea the scopes in the MS DI container weren't hierarchical until it was raised via the documentation. If you were to swap in the MS DI container (or some other container implementing IServiceProvider) your code wouldn't run right, either - because, while you might be using the MS abstractions, you were relying on an Autofac-specific implementation of the abstractions that was, apparently, incorrect.

    This is the unfortunate downside to conforming containers and common interfaces - everything has to be lowest common denominator, so you lose flexibility and features you might want.