Autofac is an awesome. NET IoC containers. It manages the dependencies between classes, so that the application can still be easily modified as the scale and complexity increase. It is implemented by treating regular .NET classes as components. I'm also a cliché about Autofac containers, and I've written a lot of articles:
Create a new project ASP.NET Core 3.1 and reference autofac-related packages through nuget, as follows:
Let's create a new ITest interface and implementation, the code is as follows:
Create a new BaseController base class controller, and other controllers inherit the abstract class, add the ITest property to the base class, and the code is as follows:
Let the WeatherForecastController inherit from the BaseController abstract class, adding the following test method:
The ConfigureContainer method in the Startup class registers the interface and sets the controller attribute input, the code is as follows:
Try to visit:The hyperlink login is visible.
NullReferenceException exception is quoted in the blank message, as shown in the following figure:
NullReferenceException: Object reference not set to an instance of an object.
PassThe constructor is injected into the ITest interface, its method is called, the test passes, and it can be called normally。
Causes of anomalies
The implementation of the Controller is more special, the Controller does not Resolve&Activate by default through its own container, it is managed by MVC itself, but Microsoft provides this method:
You can make the Controller use its own container by calling the AddControllersAsServices() method, the main source code of which is as follows:
The ConfigureServices method in the default Startup object is configured as follows:
We modify it to:
Or:
The ServiceBasedControllerActivator source code is as follows:
Once configured, load the controller directly from the DI container, the controller will parse the service from Autofac, and the property injection we configured will take effect. As shown below:
Finally, the source code address of asp.net core is attached:
The hyperlink login is visible.
(End)
|