This is the 5th day of my participation in the August More Text Challenge

Autofac is injected via constructors

As shown in the previous article, obtaining instances is done through constructors. Here we get the instance through the constructor, or we get it through the IServiceProvider constructor. This method can greatly reduce constructor parameter bloat caused by too many instances passed to the constructor. The example extends directly from the previous project, under the controller’s test API, and is used directly. Examples are shown below:

 

Set a breakpoint and run the program to see the effect. See that the IWeskyTest interface has been injected and is accessible

 

Autofac uses property injection

In the ServiceA implementation class, add IServiceB, IServiceC properties. And in the ServiceA implementation class, add a test method Hey() that calls the interface methods corresponding to the two properties. The code is as follows:

 

And Hey needs to be added to the abstract class interface IServiceA:

 

Register the service for IServiceA\B\C. Where, services that provide properties must be registered using the PropertiesAutowired mode, as shown in the following code:

 

Then rewrite the Test method in the controller to Test. The corresponding code, explanation and corresponding running results are shown in the figure below:

 

Autofac uses method injection

Rewrite the ServiceA class above to the following code. The code description is shown in figure:

 

Service registration for IServiceA and B used. As shown in the figure, method injection is provided in ServiceA, so you need to use the OnActivated method when registering ServiceA. RegisterService is a method provided by the ServiceA service that needs to be injected as a method, and IServiceB is an abstract class (interface) that needs to be injected by the method. The following uses instantaneous, but others can be used without restriction, including the non-singleton mode for ServiceB service registration.

 

Run the program. If ServiceA and ServiceB are printed, the method is successfully injected. The results of running the program are as follows:

 

Filter supports dependency injection

Start by writing a WeskyFilter that inherits from ActionFilterAttribute. Add a property-injected IServiceC and a constructor injected IServiceD.

Then implement a print under the OnActionExecuting and OnActionExecuted methods, and print the Hello method under the ServiceC instance and ServiceD instance respectively. The code is as follows:

 

Register IServiceC, D, and WeskyFilter to support dependency injection:

 

Add the filter flag above the Test method in the controller and run it directly to verify the result:

 

Printing out the contents of the filter and successfully accessing the Hello methods of ServiceC and D, as shown in the figure, indicates that dependency injection is possible in the filter.

That’s all for this article. Thanks for watching.