ASP.NET Core used in injection attribute Autofac

Some irrelevant nonsense:

  As a programmer alike (self-proclaimed), like the kind of form using annotations Spring's dependency injection or Unity characteristic form of dependency injection, of course, in the form of similar, but the results are the same, dependency injection through the property.

  ASP.NET Core used in Dependency Injection comes as a default IOC container, of course, there are inherent advantages, many still prefer to switch to Autofac as IOC container, Unity in .Net Core there are still a great advantage, but As far as I know, Unity5 has been transferred to the Foundation by Microsoft, but is itself poorly documented, translated documents, and research is even more less.

  Of course, to say a bunch of nonsense, Autofac property itself is supported by injection, but many were still using constructor injection, I recommend using the constructor itself be injected (in fact, I do not think so), because the use of property were injected, the will expose the properties of the current class (Autofac property injecting property must be public), Spring can be injected with a private, but do not know why, Autofac I use private injection came in is null, if the article wrong, I hope experts It can be noted in the message, the more people and help me progress. Thank you.

⒈ Create a new ASP.NET Core MVC program.

⒉ add NuGet package

Install-Package Autofac
Install-Package Autofac.Extensions.DependencyInjection

⒊ new entity class service abstraction, service implementation. (DAL I omitted here, on their own brain)

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 
 6 namespace DapperDemo.Models
 7 {
 8     public class User
 9     {
10         public int id { get; set; }
11         public string username { get; set; }
12         public string password { get; set; }
13         public int enabled { get; set; }
14     }
15 }

 

 1 using DapperDemo.Models;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Threading.Tasks;
 6 
 7 namespace DapperDemo.Services
 8 {
 9     public interface IUserService
10     {
11         IList<User> GetUsers();
12     }
13 }

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using DapperDemo.Models;
 6 
 7 namespace DapperDemo.Services.Impl
 8 {
 9     public class UserService : IUserService
10     {
11         public IList<User> GetUsers()
12         {
13             return new List<User>
14             {
15                 new User
16                 {
17                     id = 1,
18                     username = "fanqi",
19                     password = "admin",
20                     enabled = 1
21                 }
22             };
23         }
24     }
25 }

⒋ create a Aufofac Module, arranged injection

 1 using Autofac;
 2 using DapperDemo.Services;
 3 using DapperDemo.Services.Impl;
 4 using Microsoft.AspNetCore.Mvc;
 5 using System;
 6 using System.Collections.Generic;
 7 using System.Linq;
 8 using System.Reflection;
 9 using System.Threading.Tasks;
10 
11 namespace DapperDemo.Module
12 {
13     public class DefaultModule : Autofac.Module
14     {
15         protected override void Load(ContainerBuilder builder)
16         {
17 
18             builder.RegisterType<UserService>().As<IUserService>().PropertiesAutowired()
19                 .InstancePerLifetimeScope();
20 
21             var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
22                 .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
23             builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();
24 
25         }
26     }
27 }

⒌ modifications Startup, replace IOC, the IOC used as the default container Autofac

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Reflection;
 5 using System.Threading.Tasks;
 6 using Autofac;
 7 using Autofac.Extensions.DependencyInjection;
 8 using DapperDemo.Module;
 9 using Microsoft.AspNetCore.Builder;
10 using Microsoft.AspNetCore.Hosting;
11 using Microsoft.AspNetCore.Mvc;
12 using Microsoft.Extensions.Configuration;
13 using Microsoft.Extensions.DependencyInjection;
14 
15 namespace DapperDemo
16 {
17     public class Startup
18     {
19         public Startup(IConfiguration configuration)
20         {
21             Configuration = configuration;
22         }
23 
24         public IConfiguration Configuration { get; }
25 
26         // This method gets called by the runtime. Use this method to add services to the container.
27         public IServiceProvider ConfigureServices(IServiceCollection services)
28         {
29             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddControllersAsServices();
30             
31             // 添加 Autofac
32             var containerBuilder = new ContainerBuilder();
33 
34             containerBuilder.Populate(services);
35 
36             containerBuilder.RegisterModule<DefaultModule>();
37 
38             var container = containerBuilder.Build();
39 
40             return new AutofacServiceProvider(container);
41         }
42 
43         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
44         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
45         {
46             if (env.IsDevelopment())
47             {
48                 app.UseDeveloperExceptionPage();
49             }
50             else
51             {
52                 app.UseExceptionHandler("/Home/Error");
53             }
54 
55             app.UseStaticFiles();
56             app.UseCookiePolicy();
57 
58             app.UseMvc(routes =>
59             {
60                 routes.MapRoute(
61                     name: "default",
62                     template: "{controller=Home}/{action=Index}/{id?}");
63             });
64         }
65     }
66 }

⒍ new controller, into the abstract implementation services in the property.

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using DapperDemo.Models;
 6 using DapperDemo.Services;
 7 using Microsoft.AspNetCore.Http;
 8 using Microsoft.AspNetCore.Mvc;
 9 
10 namespace DapperDemo.Controllers
11 {
12     [Route("api/[controller]")]
13     [ApiController]
14     public class UserController : ControllerBase
15     {
16         public IUserService UserService { protected get; set; }
17 
18         [Route("get")]
19         public IList<User> GetUsers()
20         {
21             return UserService.GetUsers();
22         }
23 
24     }
25 }

⒎ test

 

Guess you like

Origin www.cnblogs.com/fanqisoft/p/10962975.html