一些无关紧要的废话:
作为一名双修程序员(自封的),喜欢那种使用Spring的注解形式进行依赖注入或者Unity的特性形式进行依赖注入,当然,形式大同小异,但结果都是一样的,通过属性进行依赖注入。
ASP.NET Core中使用了自带的Dependency Injection作为了默认的IOC容器,当然有先天的优势,很多还是喜欢切换到Autofac作为IOC容器,Unity在.Net Core中还是有很大的优势的,但据我所知,Unity5已经由微软转交到基金会了,而且本身文档很少,翻译文档以及研究的就更加少了。
当然,说了一堆废话,Autofac本身也是支持属性注入的,但是很多还是使用构造器进行注入,我本身也是推荐使用构造器进行注入(其实我不是这么想的),因为使用属性进行注入,将会暴露当前类的属性(Autofac属性注入属性必须为public),Spring可以用private进行注入的,但是不知道为什么,Autofac我使用private的时候注入进来的时候是null,如果文章有错误的话,希望高手能在留言处指出,帮助我及更多人进步。谢谢。
⒈新建一个ASP.NET Core MVC程序。
⒉添加 NuGet 包
Install-Package Autofac Install-Package Autofac.Extensions.DependencyInjection
⒊新建实体类,服务抽象,服务实现。(DAL我这里就省略了,自行脑部)
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 }
⒋新建一个Aufofac Module,配置注入
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 }
⒌修改Startup,替换IOC,使用Autofac作为默认的IOC容器
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 }
⒍新建控制器,在属性中注入服务抽象实现。
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 }
⒎测试