Finally, lost a long time to pick up the MVC, although some impressions, but still need to learn again.
Many books refer to concepts such as dependency injection, control inversion, which are designed to achieve loosely coupled layers, components, and classes.
It is common to use the repository class to separate the direct contact between the controller and model. In order to relieve the close connection between the Repository class and controller, it is usually not to define the Repository class directly and instantiate it, but to inject the specified repository through the controller's construction method.
1 Public classValuescontroller:apicontroller2 {3 4 Privateioneservices _oneservices;5 6 PublicValuescontroller (ioneservices oneservices)7 8 {9_oneservices =oneservices;Ten One}
12//.....
13}
The popular IOC containers are: ninject,autofac,unity.
A brief explanation of the use of AUTOFAC injection MVC5 and Webapi2 is now made.
1. Use Nupkg to refer to Autofac,autofac.mvc5 and autofac.webapi2
pm> install-package autofac-version 3.5.0
Pm> Install-package AUTOFAC.MVC5
Pm> install-package Autofac.webapi2 (Note: If you are using WEBAPI2 in your project, it must be webapi2 instead of WEBAPI, or "override member" will appear at run time Autofac.Integration.WebApi.AutofacWebApiDependencyResolver.BeginScope () "Violates the inheritance security rule. The overriding method's security accessibility must match the security accessibility of the overridden method. Error )
2. Register the components.
var builder=new containerbuilder ();
Builder. Registerapicontrollers (assembly.getexecutingassembly ());//Registration API Container implementation
Builder. Registercontrollers (assembly.getexecutingassembly ());//implementation of the registered MVC container
Builder. Registerassemblytypes (AppDomain.CurrentDomain.GetAssemblies ())//Find the type in the assembly that ends with services
. Where (t = t.name.endswith ("Services"))
. Asimplementedinterfaces ();
Builder. Registerassemblytypes (AppDomain.CurrentDomain.GetAssemblies ())//Find the type in the assembly that ends with repository
. Where (t = t.name.endswith ("Repository"))
. Asimplementedinterfaces ();
3. Create a container for later use.
var container=builder. Build ();
4. Create a lifetime scope from container.
5. Use this lifetime Scope to parse an instance of a component.
New Autofacwebapidependencyresolver (container); // Registering API containers requires the use of Httpconfiguration objects Dependencyresolver.setresolver (new Autofacdependencyresolver (container)); // Registering an MVC container
6. In the Register method of the Webapiconfig class, call the above step code and pass in the Httpconfiguration object.
The advantage of AUTOFAC is that it can be decoupled at once without the need for configuration, and AUTOFAC better implements the concept of "contract greater than Configuration" in MVC.
AUTOFAC relies on injecting MVC5 and Webapi2