0

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 ?

Jend DimShu
  • 87
  • 1
  • 5

1 Answers1

1

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

Riaz Raza
  • 382
  • 1
  • 14
  • Yes it resolved if i change it to InstancePerLifetimeScope, however a unique EFDBcontext is created for each repository object which is indirect dependency in the mediator command handler. SingleInstance work well but it will be reuse in the next request (which ideally should be disposed each http request). The goal is to make EFDbContext lifetime as long as the http request and share a single instance across the repository. – Jend DimShu Feb 20 '19 at 10:50
  • After a full day searching, i think mediatr does not fully integrate with asp.net web api request while asp.net core is fully integrated(supported my goal 1 ef context per request). I managed to save and get entity relationship on each repository, not ideal solution but work at the moment. I mark your comment as answer since mediatr does not support request response as you explained. Thanks Riaz – Jend DimShu Feb 20 '19 at 12:44