This article is a mirror article of machine translation, please click here to jump to the original article.

View: 26892|Reply: 0

[.NET Core] ASP.NET Core uses Autofac to implement IOC injection

[Copy link]
Posted on 5/7/2019 4:32:23 PM | | | |
ASP.NET Core dependency injection uses the IOC container that comes with it
https://www.itsvse.com/thread-7562-1-1.html
(Source: Architect_Programmer)

ASP.NET Core uses Autofac to implement IOC injection
https://www.itsvse.com/thread-7563-1-1.html
(Source: Architect_Programmer)

ASP.NET Core uses Autofac to implement AOP interception
https://www.itsvse.com/thread-7566-1-1.html
(Source: Architect_Programmer)

The IOC container that comes with ASP.NET Core is lightweight, and there are not many functions, but only basic functions.

This article will use Autofac to explain both constructors and attribute injection.

Autofac is an awesome IoC container for Microsoft .NET 4.5, Silverlight 5, Windows Store apps, and Windows Phone 8 apps. It can manage dependencies between classes so that the application can be easily modified as the scale and complexity grow. Implement the .

The .NET Core version of the project is: 2.1.301

Install Autofac.Extensions.DependencyInjection

Install via nuget with the following command:



We wrote 3 interfaces and 3 implementation classes casually, as follows:



Controller constructor injection

First, let's modify the ConfigureServices code in Startup as follows:

Note: The return value of ConfigureServices has been changed to IServiceProvider.

Controller Code:

Run the project as shown below:



Controller Autofac attribute injection

Modify the ConfigureServices method in Startup as follows:

Controller Code:

Run the project as shown below:



Key points to note:

  • services. AddMvc(). SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddControllersAsServices();
  • publicITestService1 _testService1 { get; set; }


Because I set the service interface to private at the beginning, the injection is always null.

Resources:The hyperlink login is visible.




Previous:ASP.NET Core dependency injection uses the IOC container that comes with it
Next:ASP.NET Core ILogger Log Usage Tutorial
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com