NET Core source code to implement dependency injection through AUTOFAC

Source: Internet
Author: User

Read Catalogue

    • First, preface
    • Second, the use of AUTOFAC
    • Third, the last
Back to catalogue one, preface

In the previous article, "ASP. NET Core integration Autofac and Castle for automatic AOP interception", we talked about how to use AUTOFAC to take over except for Asp.netcore's own IOC container. IServiceProvider for Dependency Injection.

I've recently had an idea to implement dependency injection of the controller's property values in ASP. NET MVC core. But we searched the Microsoft.Extensions.DependencyInjection class library and found no corresponding method, and after looking at the source code, it was discovered that it was a dependency injection for the constructor, and there was no dependency injection on the property or field.

The two methods that the authorities have given us to get the results of dependency injection:activatorutilities.createinstance and iserviceprovider.getservice, the difference between the two methods, Here I do not elaborate, interested friends can go to see the source code of these two classes: ServiceProvider and activatorutilities, but there is always two ways to create an object without injecting property values.

Simply call these two methods: first in the Startup.configureservices function, add the statement Services.addtransient<iuser, myuser> ();

  1.   1. iuser User = activatorutilities. CreateInstance(serviceprovider, typeof(iuser));
  2.   2. iuser User = serviceprovider. GetService(typeof(iuser))

Both functions return the same result, and if there is an interface type in the constructor of the MyUser, the two methods also do dependency injection, but none of the created object properties are injected. But the two methods are still different in principle, activatorutilities constructs the constructor of the type by constructing the Expressiontree and creates the object, and uses the IServiceProvider injected constructor Whereas ServiceProvider is a recursive creation of objects by the callsite of the life cycle of the dependency injection.

If it's better to say that way, it's obvious that IServiceProvider is an interface, and Activatorutilities is a set of methods, and the ASP. The Di life cycle in core is full of serviceprovider, and its ability to expand is not explained.

Back to Directory II, use AUTOFAC

It makes the use of AUTOFAC in this example to be lazy, mainly because AUTOFAC has supported the dependency injection of attributes. However, it is not possible to use it directly, and by studying the source code of ASP. I found a workaround and used AUTOFAC to complete the dependency injection of the Controller property.

As mentioned in the previous article Autofac, AUTOFAC is done by modifying the return value of the Startup.configureservices function, and the return value is modified from void to IServiceProvider.

  1. Public IServiceProvider configureservices(iservicecollection services)
  2. {
  3. var builder = new containerbuilder();
  4. Services. Addmvc();
  5. Builder. Populate(services);
  6. this. Applicationcontainer = builder. Build();
  7. return new autofacserviceprovider(this. Applicationcontainer);
  8. }

By returning the Autofacserviceprovider type of ISERVICEPROVIDER,AUTOFAC, the serviceprovider is taken over by decorative mode. But after taking over the IServiceProvider, we will find that this does not inject the attribute value, after studying the ASP. NET core source code, the following ideas are collated:

1. Find the type of all controllers
  1. var manager = new Applicationpartmanager();
  2. Manager. Applicationparts. Add(new AssemblyPart(Assembly));
  3. Manager. FeatureProviders. Add(new controllerfeatureprovider());
  4. var feature = new controllerfeature();
  5. Manager. Populatefeature(feature);

All program components are managed through applicationpartmanager,asp.net Core, where Assemblypart is an assembly component, which means that the ASP. MVC looks for the type of controller or other type of use in this assembly. We can also use this method to add an assembly that splits the MVC project into two separate projects, such as a controller project and a View project.

Controllerfeatureprovider This class to look at a name and know it is used to find the controller type. Let's take a look at its code:

  1. Public void populatefeature(IEnumerable<applicationpart> Parts,controllerfeature feature)
  2. {
  3. foreach (var part in parts. OfType<iapplicationparttypeprovider>())
  4. {
  5. foreach (var type in part. ) Types)
  6. {
  7. if (iscontroller(type) &&! Feature. Controllers. Contains(type))
  8. {
  9. Feature. Controllers. Add(type);
  10. }
  11. }
  12. }
  13. }
2. Registering the controller type with AUTOFAC
    1. Builder. Registertypes(feature. Controllers. Select(ti = ti. Astype()). ToArray()). propertiesautowired();

AUTOFAC is registered with the controller in the Controllerfeature by IOC and uses propertiesautowired to turn on attribute injection.

3. Modify the default controller creator and use AUTOFAC's serviceprovider to complete the creation of your controller.

This is also the most important step by viewing the source code. ASP. NET core uses the Defaultcontrolleractivator class to create the controller by default But finding the CREATE function for this class publishes it actually calls Activatorutilities to create the object. As mentioned earlier, when creating a type object, Iserviceprovdier is only responsible for finding and injecting parameters in the constructor, and creating the object is created by Activatorutilities. This also makes use of the AUTOFAC replacement serviceprovider, which means that activatorutilities does not have an extension point to replace with the method we provide, so it is not possible to inject the problem.

The following code is added to Services.addmvc () before, as follows:

    1. Services. Replace(servicedescriptor. Transient<icontrolleractivator, servicebasedcontrolleractivator> ());

In fact, it is to use servicebasedcontrolleractivator to replace the default defaultcontrolleractivator; Take a look at its source code, just a moment to understand:

  1. public Object Create(controllercontext actioncontext)
  2. {
  3. if (actioncontext = = null)
  4. {
  5. throw new ArgumentNullException(nameof(actioncontext));
  6. }
  7. var controllertype = actioncontext. Actiondescriptor. Controllertypeinfo. Astype();
  8. return actioncontext. HttpContext. Requestservices. Getrequiredservice(controllertype);
  9. }

Here the requestservices is IServiceProvider so all understand, here is the use of we have replaced with provider.

Finally, add a demo to see if the attribute user is injected with a value:

  1. public class homecontroller : Controller
  2. {
  3. public iusermanager User { set; get; }
  4. public iactionresult Index()
  5. {
  6. User. Register("Hello");
  7. return View();
  8. }
  9. }

Back to table three, last

ASP. NET core source code is really a good material to learn, each component is an extension, each component has a set of widgets; True component Development!

  

Demo git address: Https://github.com/maxzhang1985/AutofacCastle.AspNetCore.Demo

GITHUB:HTTPS://GITHUB.COM/MAXZHANG1985/YOYOFX If you feel you can also invite the Star , Welcome to communicate together.

Communication groups for. NET Core and YOYOFX: 214741894

  

NET Core source code to implement dependency injection through AUTOFAC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.