一些無關緊要的廢話:
作為一名雙修程序員(自封的),喜歡那種使用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我這里就省略了,自行腦部)
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DapperDemo.Models { public class User { public int id { get; set; } public string username { get; set; } public string password { get; set; } public int enabled { get; set; } } }
using DapperDemo.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DapperDemo.Services { public interface IUserService { IList<User> GetUsers(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DapperDemo.Models; namespace DapperDemo.Services.Impl { public class UserService : IUserService { public IList<User> GetUsers() { return new List<User> { new User { id = 1, username = "fanqi", password = "admin", enabled = 1 } }; } } }
⒋新建一個Aufofac Module,配置注入
using Autofac; using DapperDemo.Services; using DapperDemo.Services.Impl; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace DapperDemo.Module { public class DefaultModule : Autofac.Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<UserService>().As<IUserService>().PropertiesAutowired() .InstancePerLifetimeScope(); var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes() .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray(); builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired(); } } }
⒌修改Startup,替換IOC,使用Autofac作為默認的IOC容器
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Autofac; using Autofac.Extensions.DependencyInjection; using DapperDemo.Module; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace DapperDemo { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddControllersAsServices(); // 添加 Autofac var containerBuilder = new ContainerBuilder(); containerBuilder.Populate(services); containerBuilder.RegisterModule<DefaultModule>(); var container = containerBuilder.Build(); return new AutofacServiceProvider(container); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
⒍新建控制器,在屬性中注入服務抽象實現。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DapperDemo.Models;
using DapperDemo.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace DapperDemo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
public IUserService UserService { protected get; set; }
[Route("get")]
public IList<User> GetUsers()
{
return UserService.GetUsers();
}
}
}
⒎測試