一、配置Autofac替换内置DI
- 安装Nuget包:Autofac,Autofac.Extensions.DependencyInjection
- Program.cs中CreateHostBuilder方法后加上.UseServiceProviderFactory(new AutofacServiceProviderFactory()) ; 告诉程序要使用Autofac。
- Startup.cs中增加方法ConfigureContainer(ContainerBuilder containerBuilder),实例注入的地方,配置完成。同时防止startup.cs代码过多,建一个Module把注入代码搬走,新建AutofacRegisterModule.cs类把ConfigureContainer的代码移过去。而在ConfigureContainer中调用即可。
// 然后在startup类中新建ConfigureContainer方法,配置
public void ConfigureContainer(ContainerBuilder builder)
{
// 直接用Autofac注册我们自定义的
builder.RegisterModule(new AutofacRegisterModule());
}
- AutofacRegisterModule.cs类 注入仓储层和服务层
public class AutofacRegisterModule : Autofac.Module
{
/// <inheritdoc/>
//重写Autofac管道Load方法,在这里注册注入
protected override void Load(ContainerBuilder builder)
{
var basePath = AppContext.BaseDirectory;
//如需加载实现的程序集,将dll拷贝到bin目录下即可,不用引用dll
var tmp = Path.Combine(basePath, "XXX.XXX.IService.dll");
var IServices = Assembly.LoadFrom(tmp);
var Services = Assembly.LoadFrom(Path.Combine(basePath, "XXX.XXX.Service.dll"));
var IRepository = Assembly.LoadFrom(Path.Combine(basePath, "XXX.XXX.IRepository.dll"));
var Repository = Assembly.LoadFrom(Path.Combine(basePath, "XXX.XXX.Repository.dll"));
//根据名称约定(服务层的接口和实现均以Service结尾),实现服务接口和服务实现的依赖
builder.RegisterAssemblyTypes(IServices, Services)
.Where(t => t.Name.EndsWith("Service") || t.Name.EndsWith("Work"))
.AsImplementedInterfaces();
//根据名称约定(数据访问层的接口和实现均以Repository结尾),实现数据访问接口和数据访问实现的依赖
builder.RegisterAssemblyTypes(IRepository, Repository)
.Where(t => t.Name.EndsWith("Repository") || t.Name.EndsWith("Work"))
.AsImplementedInterfaces();
//获取所有控制器类型并使用属性注入
Type[] controllersTypeAssembly = typeof(Startup).Assembly.GetExportedTypes()
.Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
builder.RegisterTypes(controllersTypeAssembly).PropertiesAutowired();
}
}
二、构造函数注入
新建IUserService,类UserService,控制器UserController
代码语言:javascript复制public interface IUserService
{
public string GetUserName();
}
代码语言:javascript复制 public class UserService
{
public string GetUserName()
{
return "张三";
}
}
代码语言:javascript复制 public class UserController : Controller
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
public IActionResult Index()
{
string name = _userService.GetUserName();
return Content(name);
}
}
在上面的ConfigureContainer方法把UserService注入进来,默认是瞬时注入 瞬时注入:containerBuilder.RegisterType().As().InstancePerDependency();; 单例注入:containerBuilder.RegisterType().As().SingleInstance(); 生命周期注入: containerBuilder.RegisterType().As().InstancePerLifetimeScope();
代码语言:javascript复制/// <summary>
/// Autofac注册服务的地方,Autofac会自动调用
/// </summary>
/// <param name="containerBuilder"></param>
public void ConfigureContainer(ContainerBuilder containerBuilder)
{
//注册服务
containerBuilder.RegisterType<UserService>().As<IUserService>();
}
访问/User/Index,_userService成功注入,正确获取结果。