Everyone familiar with IOC containers knows that the most depressing thing in the development process is that when you add a service, you need to register the service, and some useCodeInjection, some of which are xml configuration injection. No matter which type of injection, developers often forget the injection,
If your page sends a request directly, you will get an error similar to the following page:
<-_ <-
If the service is used for Ajax requests, then you will be miserable, because the page only does not respond and you only need to view the error log.
So I tried to find a way to avoid injecting every service, but the system automatically injects the service.
The place in the red lines is the implementation of automatic injection code. We are glad that autofac provides a registerassemblytypes method. It goes back to scan all the DLL and registers each class as the interface it implements ....
Since automatic injection can be performed, the interface and class definition must be regular. From the code above, we can see that the basetype variable is of the idependency interface type.
The idependency interface is as follows:
Any other interface must inherit this interface. For example, we define an interface imodelcar:
Imodelcar implementation class:
Automatic injection principles:
First, find all the DLL, find the class that implements the idependency interface, and then use registerassemblytypes for injection.
Try calling in controller:
You can see that the _ carmodel instance after resolution is modelcar ..
Download Demo:Https://github.com/nicholaspei/MvcApplication5