How to resolve Autofac per-request service from custom attribute
<p>I have configured my EF context configured like so</p>

<pre><code>        b.RegisterAssemblyTypes(webAssembly, coreAssembly)
            .Where(t =&gt; t.IsAssignableTo&lt;DbContext&gt;())
            .InstancePerLifetimeScope();
</code></pre>

<p>I would like to use it from a custom authorization attribute that hits the database using my EF context. This means no constructor-injection. I achieve this by using <a href="https://www.nuget.org/packages/CommonServiceLocator/" rel="nofollow noreferrer">CommonSeviceLocator</a></p>

<pre><code>        var csl = new AutofacServiceLocator(container);
        ServiceLocator.SetLocatorProvider(() =&gt; csl);
</code></pre>

<p>...</p>

<pre><code>        var user = await ServiceLocator.Current
           .GetInstance&lt;SiteContext&gt;().FindAsync(id);
</code></pre>

<p>I am finding that this fails with a "multiple connections not supported" error if the browser issues two simultaneous requests to routes using this attribute. It seems like this might be <a href="https://stackoverflow.com/a/23356038/5056">due to what is mentioned in this answer</a>. My guess is that <code>ServiceLocator</code> resolves from the root scope rather than the web request scope and the two request are conflicting (either request in isolation works fine).</p>

<p>This seems confirmed by that when I change to <code>InstancePerRequest()</code> I get this from any invocation of the attribute.</p>

<pre><code> Autofac.Core.DependencyResolutionException No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is
 being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container  itself.
</code></pre>

<p>So it seems like maybe <code>ServiceLocator</code> is simply not the way to go. </p>

<p>How do I resolve the request-scoped <code>SiteContext</code> from inside the attribute (using a service-locator pattern)?</p>