Kohiki
Before ASP 5 (VNext), the era of MVC 4/5 and Web API 2, MVC and the Web API framework had very similar designs to each other, but were implemented in different codes. Now, the ASP. NET 5 integrates MVC, Web API, and Web Pages program models into a single framework, collectively referred to as MVC 6.
Another highlight of the ASP. NET 5 is the Dependency injection container. Prior to this, the MVC and Web API Framework support for DI was relatively weak, with the protagonist being the Idependencyresolver interface.
The own di container for ASP. NET 5 May already be able to meet most of the DI Foundation operations, which means that in the future we may be less dependent on other DI frameworks, such as Unity, AUTOFAC.
Here we go. Kind the DI container of the ASP. NET 5.
Tools you need: Visual Studio Preview
Note : Because the ASP. NET 5 is still in beta, Visual Studio 2015 is also a preview version, so the Operation screen and program examples in this article may be somewhat out of date with the future official version.
Practice Step 1: Build the project
Open Visual Studio 2015 and build a new ASP. NET WEB Application project, reference:
The project name is named Dependencyinjectiondemo. After pressing OK, then select Template "asp.net 5 empty":
After the project is established, take a look at some of the things in solution Explorer:
The Project.json in the root directory is the configuration file for this project, which contains the frameworks and components on which this project depends. The Startup.cs contains the initialization work that is required to be performed when the application is activated.
Step 2: Add the necessary components
When the project was first established, the Project.json content is as follows:
{ "Webroot": "Wwwroot" , "version": "1.0.0-*" "exclude" : [ "Wwwroot" ], "Packexclude" : [ "**.kproj" "**.user" " **.VSPSCC "", "Dependencies" " Microsoft.AspNet.Server.IIS ":" 1.0.0-beta1 ",}, "Frameworks" " aspnet50 ": {}, "Aspnetcore50" : {}}}
We have to include the ASP. NET MVC component in the "dependencies" section: "MICROSOFT.ASPNET.MVC": "6.0.0-beta1" (Your development environment may be a different version number). All of these words have to be tapped in, but fortunately, Visual Studio has smart hints, such as:
Note: If the smart prompt does not appear, you can press ALT + RIGHT ARROW key to make it appear.
After you enter a colon, the version is then prompted, such as:
While moving to the bottom, you can choose the latest beta version, but it does not necessarily work well in your current development environment. Be on the safe side, or choose the top "6.0.0-beta1".
After the modifications are complete, the contents of the "dependencies" block will look like this:
"Dependencies": { "Microsoft.AspNet.Server.IIS": "1.0.0-beta1", "MICROSOFT.ASPNET.MVC" : "6.0.0-beta1"},
Description
- Microsoft.AspNet.Server.IIS-because we want to use IIS to do the loading platform for this application, we must join this package.
- MICROSOFT.ASPNET.MVC-This is the core suite of MVC and Web APIs.
Step 3: Join the Web API component to the ASP .
To open Startup.cs, refer to the following example to modify the code:
usingSystem;usingMicrosoft.AspNet.Builder;usingMicrosoft.AspNet.Http;usingMicrosoft.Framework.DependencyInjection;//don't forget about this!usingMicrosoft.AspNet.Hosting;//don't forget about this! namespacedependencyinjectiondemo{ Public classStartup { Public voidConfigure (Iapplicationbuilder app) {app. Usemvc (); } Public voidconfigureservices (iservicecollection services) {services. Addmvc (); } }}
Description
- The Configure method has an incoming parameter app, and the type is Iapplicationbuilder. It uses its Usemvc method to add the Mvc/web API component to the application's pipeline job flow. The ASP. NET Framework proactively calls this method when the application is activated.
- The Configureservices method is also called by the ASP. NET Framework, where we can set the services required by the application (including registering the type with the DI container). Note the incoming parameter services for this method, the type is iservicecollection; it is the DI container of the ASP. NET 5. We can use this container to annotate the type correspondence of dependent objects, and this section will have an example program later.
Note: The Iservicecollection interface is subordinate to the namespace Microsoft.Framework.DependencyInjection.
Step 4: Join the API Controller
In the Solution Explorer, a folder is created under the project's root directory: Controllers. Then right-click on this folder and choose Add-New Item. Select the "web API Controller class" in the newly opened dialog and name the file ValuesController.cs. Reference:
The resulting code is roughly as follows:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingMICROSOFT.ASPNET.MVC;namespacedependencyinjectiondemo.controllers.controllers{[Route ("Api/[controller]")] Public classValuescontroller:controller {//get:api/values[HttpGet] Publicienumerable<string>Get () {return New string[] {"value1","value2" }; } //omit the remaining get/post/put/delete methods. }}
Ok! Now press F5 or CTRL+F5 to see if the application works. Note that the address bar of the browser must be manually modified to look like this:
http://[Host Name: Port number]/api/values
If the error message does not appear, you can proceed to the next step.
Step 5: Write the service category for the test
Write a simple category as the object injected into the controller. As shown below:
namespace dependencyinjectiondemo{ publicinterface itimeservice { Stringget;} } Public class Timeservice:itimeservice { publicstring now { get { return DateTime.Now.ToString (); }}}
The code is simple enough to explain.
Step 6: Inject the dependent object to the Controller constructor
Modify the Valuescontroller category so that it looks like this:
Public classvaluescontroller:controller{Private ReadOnlyItimeservice _timeservice; PublicValuescontroller (Itimeservice timeservice) {_timeservice=Timeservice; } //get:api/values[HttpGet] Publicienumerable<string>Get () {return New string[] {_timeservice.now}; } //omit the remaining get/post/put/delete methods. }
This means that we want the ASP to be able to inject the Itimeservice object it needs when it builds the controller object. In DI terminology, "constructive injection" (Constructor injection) is used to avoid the binding of our API Controller to specific implementation categories--valuescontroller relies on an abstract Itimeservice interface , rather than the representational category Timeservice.
To execute the application again, look, because the MVC framework cannot find the default constructor for Valuescontroller, the browser should display an error message such as:
The workaround is simple, just register the implementation category for the Itimeservice type in your Startup class's Configureservices method.
Public class Startup { publicvoid Configure (Iapplicationbuilder app) { app. Usemvc (); } Public void configureservices (iservicecollection services) { services. Addmvc (); Services. addscoped// Add this line! } }
Here is the Iservicelocation extension method addscope to the ASP. NET-band container registration type correspondence, meaning: When you encounter the need to Itimeservice objects, use Timeservice to establish object entities.
In addition, it is possible to guess from the name of the method that the Addscope method has another meaning: in the future, when the container builds the Itimeservice object (in DI terms, it is "parsing itimeservice"), it creates a "live within a certain range" object. For this example, this particular scope is the scope of an HTTP request.
As a result, when the MVC framework establishes Valuescontroller, it discovers that its constructor requires a Itimeservice object, and the MVC framework takes a Itimeservice object with its own container and then passes the object in Valuescont The roller constructor.
Execute the application again, this time it should be able to execute smoothly. Execution results such as:
Very simple, huh? This is completely useless to the third-party DI framework.
Using the same technique, you can inject any object into your Controller category, such as the various services/components of the application layer (application layers).
Conclusion
The ASP. NET 5 DI container supports four life cycle modes: Instance, Singleton, Transient, Scoped. The addscoped method used in this example is Scoped, or the Per request life cycle pattern, that is, the object only survives within the scope of the current request, and the same object entity is shared within the same request scope.
To learn more about the DI features and limitations of ASP. NET 5, refer to the following articles:
- Dependency injection in ASP. VNext
- Getting started with ASP. NET 5 MVC 6 Web API & Entity Framework
- ASP vNext Dependency Injection lifecycles
ASP. NET 5 (VNext) Sledgehammer: self-carrying DI container