A, ASP.NET Core comes with its own IOC container
After ASP.NET Core itself has integrated a lightweight IOC container, developers only need to define an interface, use the method in ConfigureServices Startup.cs's binding method corresponds to the life cycle of the common methods are as follows
1 services.AddTransient<IApplicationService,ApplicationService> 2 3 services.AddScoped<IApplicationService,ApplicationService> 4 5 services.AddSingleton<IApplicationService,ApplicationService>
For the above three DI injection mode,
- Transient
Transient services are created on every request, it is best used for lightweight stateless services (such as our ApplicationService and Repository Services) - Scoped
Scoped services are created on every request, life cycle times across the entire request - Singleton
name implies, Singleton (singleton) service request is created the first time (or when we create an instance specified in ConfigureServices and operating method), subsequent requests will follow each service has been created. If the application developer needs singleton service scenario, please designed to allow the container to operate services of the service life cycle, instead of manually implemented singleton design pattern is then operated by the developer in the custom class. - Description from paragraph: https://www.cnblogs.com/Wddpct/p/5764511.html
If we use the built-in container, the code looks more clear, but if too much of the interface class situation, it will appear as shown, each interface and implementation are required to "manual" injection, if injected once missed it the project will not lead to the correct operation and so on.
Two, AutoFac batch injection
1, package installation requires injection AutoFac
2, a new configuration name or other AutoFacxxxx / injection file
. 1 Private static Object _lock = new new Object (); 2 /// <Summary> . 3 /// // Create a new IOC container . 4 /// </ Summary> . 5 Private static the IContainer _container; . 6 /// <Summary> 7 /// container AutoFac determines whether there exists the direct use, there is created . 8 /// </ Summary> . 9 /// <param name = "svrname"> service assembly name </ param> 10 / // <Returns> </ Returns> . 11 public staticThe Register the IServiceProvider (IServiceCollection Services, String [] svrNames) 12 is { 13 is IF (_container == null ) 14 { 15 Lock (_lock) 16 { . 17 IF (_container == null ) 18 is { . 19 // the IOC configured to register a container of AutoFac builder container 20 is ContainerBuilder builder = new new ContainerBuilder (); 21 is builder.Populate (Services); 22 is List <the Type> types = new new List <the Type> (); 23 is the foreach ( String Item in svrNames) 24 { 25 // Load Interface service implementation layer. 26 is Assembly SvrAss = the Assembly.Load (Item); 27 // reflection scan in the assembly of all the classes, this assembly to obtain a set of all classes. 28 types.AddRange (SvrAss.GetTypes ()); 29 } 30 // tell AutoFac container, creating stypes this collection object instances of all classes in a Http request context, a component instance share 31 Autofac.Builder.IRegistrationBuilder < Object .., Autofac.Features.Scanning.ScanningActivatorData, Autofac.Builder.DynamicRegistrationStyle> = builder.RegisterTypes Register (types.ToArray ()) AsImplementedInterfaces () InstancePerLifetimeScope () PropertiesAutowired ();. // specified All instances of this class objects set stypes created, stored in the form of the interface 32 33 is // create a real AutoFac work container 34 is _container = builder.Build (); 35 } 36 } 37 [ } 38 is return new new AutofacServiceProvider ( _container); 39 }
3, call Statup, we need to modify the original ConfigureServices return type for the IServiceProvider
/// support multiple Service injection
return AutoFacConfig.Register (Services, new new String [] { " Business.Service " , " Business.Services " });
Third, code examples
1, project structure
2, Model layer
public class Student { public int StuNo { get; set; } public string StuName { get; set; } public int StuAge { get; set; } }
3、Interface-》IStudentService
public interface IStudentService { List<Student> GetStudentList(); }
4、Service->StudentService
public class StudentService : IStudentService { public List<Student> GetStudentList() { List<Student> list = new List<Student>(); list.Add(new Student() { StuNo = 1, StuAge = 18, StuName = "张三" }); list.Add(new Student() { StuNo = 1, StuAge = 17, StuName = "王麻子" }); return list; } }
5、Controller->StudentController
[Route("api/[controller]")] [ApiController] public class StudentController : ControllerBase { IStudentService _studentService; /// <summary> /// 构造函数注入 /// </summary> /// <param name="studentService"></param> public StudentController(IStudentService studentService) { _studentService = studentService; } public object GetStudent() { var list = _studentService.GetStudentList(); return list; } }
6、运行结果