Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac scope in ASP.NET Core appears to differ between middleware

When registering an object with Autofac and resolving in middleware and again in the MVC middleware via a controller, the instance is different. Instances are registered per lifetime scope.

I've popped a repro project here https://github.com/jakkaj/AutofacResolveIssue.

The app sets a value to the IUserService in the middleware, then try to read that value in the ValuesController later.

This same technique worked in older versions of ASP.NET with autofac. Any ideas what's going on?

like image 785
Jordan Avatar asked Jul 18 '16 04:07

Jordan


People also ask

What is Autofac in asp net core?

Autofac is a . Net-based IoC container. When classes interact with one another, it manages the dependencies between them that allow applications to remain flexible as they grow in size and complexity. Autofac is the most widely used DI/IoC container for ASP.NET, and it is fully compatible with.NET Core as well.

Why use Autofac?

AutoFac provides better integration for the ASP.NET MVC framework and is developed using Google code. AutoFac manages the dependencies of classes so that the application may be easy to change when it is scaled up in size and complexity.

What is IApplicationBuilder in .NET core?

IApplicationBuilder An object that provides the mechanisms to configure an application's request pipeline.


1 Answers

Okay, so I made the mistake of injecting my dependency in to the constructor of the middleware.

You should inject dependencies into the Invoke.

The entire middleware object is singleton across all app instances!

like image 137
Jordan Avatar answered Jan 21 '23 13:01

Jordan