一些無關緊要的廢話:
作為一名雙修程序員(自封的),喜歡那種使用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 }
⒎測試