Search code examples
c#asp.net-web-api2autofacmediatr

Integrate Autofac with mediatr ASP.NET Web API2


I develop an app on asp.net api2 with autofac and mediatR, currently facing some issue with the dependency injection.

// This is registered in the global.asax file and working properly in the controller level //i'm trying to register the entity framework context as instance per request builder.RegisterType<EFContext>().InstancePerRequest();

However when sending the command throught MediatR pipeline, i get an exception because MetdiatR service provider cannot read the http request scope.

Below code is also located in the global asax file.

builder.Register<ServiceFactory>(context =>
            {
                var componentContext = context.Resolve<IComponentContext>();
                return t => { object o;

                    return componentContext.TryResolve(t, out o) ? o : null; };
            });

as the delegate function for service locator is called it throw an error saying that No scope with a Tag matching "AutofacWebRequest" is visible from the scope in....

is there any work around to make mediatr ServiceFactory aware of the autofact InstancePerRequest scope ?


Solution

  • Use InstancePerLifetimeScope instead for resolving entity framework context.

    I haven't used mediatR but seems like it doesn't follow the request response pattern, due to which Autofac can't associate any Request Lifetime with it.

    Note that the difference between Request Scope and Lifetime Scope in Autofac is only that Autofac will treat a request as a lifetime.

    You can read further about scopes from here, https://autofaccn.readthedocs.io/en/latest/lifetime/instance-scope.html