一些无关紧要的废话:
作为一名双修程序员(自封的),喜欢那种使用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我这里就省略了,自行脑部)
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;namespaceDapperDemo.Models
{public classUser
{public int id { get; set; }public string username { get; set; }public string password { get; set; }public int enabled { get; set; }
}
}
usingDapperDemo.Models;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;namespaceDapperDemo.Services
{public interfaceIUserService
{
IListGetUsers();
}
}
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingDapperDemo.Models;namespaceDapperDemo.Services.Impl
{public classUserService : IUserService
{public IListGetUsers()
{return new List{newUser
{
id= 1,
username= "fanqi",
password= "admin",
enabled= 1}
};
}
}
}
⒋新建一个Aufofac Module,配置注入
usingAutofac;usingDapperDemo.Services;usingDapperDemo.Services.Impl;usingMicrosoft.AspNetCore.Mvc;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Reflection;usingSystem.Threading.Tasks;namespaceDapperDemo.Module
{public classDefaultModule : Autofac.Module
{protected override voidLoad(ContainerBuilder builder)
{
builder.RegisterType().As().PropertiesAutowired()
.InstancePerLifetimeScope();var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
.Where(type=> typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();
}
}
}
⒌修改Startup,替换IOC,使用Autofac作为默认的IOC容器
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Reflection;usingSystem.Threading.Tasks;usingAutofac;usingAutofac.Extensions.DependencyInjection;usingDapperDemo.Module;usingMicrosoft.AspNetCore.Builder;usingMicrosoft.AspNetCore.Hosting;usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.Extensions.Configuration;usingMicrosoft.Extensions.DependencyInjection;namespaceDapperDemo
{public classStartup
{publicStartup(IConfiguration configuration)
{
Configuration=configuration;
}public IConfiguration Configuration { get; }//This method gets called by the runtime. Use this method to add services to the container.
publicIServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddControllersAsServices();//添加 Autofac
var containerBuilder = newContainerBuilder();
containerBuilder.Populate(services);
containerBuilder.RegisterModule();var container =containerBuilder.Build();return newAutofacServiceProvider(container);
}//This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public voidConfigure(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 GetUsers()
{
return UserService.GetUsers();
}
}
}
⒎测试