Autofac: Link from SingleInstance'd type to HttpRequestScoped

I have an application where a shared object needs an object reference to request.

Shared: Engine
                |
Per Req: IExtensions ()
                |
             Request

If I try to type IExtensions

directly into the constructor Engine

, even how Lazy(Of IExtension)

, I get "The [Query] scoped mismatch is visible from the scope where the instance was queried." an exception when it tries to instantiate each IExtension

.

How do I instantiate HttpRequestScoped and then inject it into a shared instance?

Would it be considered good practice to set it to a Request

factory (and therefore inject it Engine

into RequestFactory

)?

+1


source to share


1 answer


Due to general life requirements, Engine

you cannot inject extended query extensions into it. What you may have is a method or property in Engine that will actively resolve a collection of extensions from the current request scope.

So, first Engine

let's take the constructor dependency:

public class Engine
{
    public Engine(..., Func<IExtensions> extensionsPerRequest) 
    {
        _extensionsPerRequest = extensionsPerRequest;
    }


    public IExtensions Extensions
    {
       get { return _extensionsPerRequest(); }
    }
 }

      



And then in your Autofac registration:

builder.Register<Func<IExtensions>>(c => RequestContainer.Resolve<IExtensions>());

      

+1


source