Asp.Net.Core5
内置IOC容器
一,IServiceCollection 依赖注入
仅支持构造函数注入
1,在Startup.cs 中 ConfigureServices方法注入服务
services.AddTransient<Interfaces.IUser, Services.UserService>();
public void ConfigureServices(IServiceCollection services) { #region IOC 注册抽象和具体的依赖关系 services.AddTransient<Interfaces.IUser, Services.UserService>(); #endregion services.AddRazorPages().AddRazorRuntimeCompilation(); services.AddSession();//注册Session services.AddControllersWithViews(); }
2,设置私有变量,构造函数设置参数并将值赋值给私有变量
private readonly Interfaces.IUser userService = null; public UserController( Interfaces.IUser iUser ) { this.userService = iUser; }
3,调用方法
public IActionResult Index() { base.ViewBag.Name= userService.GetName(); return View(); }
4,在注册服务后,视图中通过关键字@inject 获取实例
@using AspNetCore5Demo.Interfaces;
@inject IUser iuser
@{
iuser.GetName();
}
二,IServiceProvider 注入
1,构造函数中设置类型为 IServiceProvider 的参数,并赋值给(私有变量)
private readonly IServiceProvider service = null; public UserController( IServiceProvider serviceProvider ) { this.service = serviceProvider; }
2,创建对象,并调用方法
public IActionResult Index() { Interfaces.IUser user = (Interfaces.IUser)service.GetService(typeof(Interfaces.IUser)); user.GetName(); return View(); }