.net 动态从容器中获取对象实例 IOC 依赖注入

  1. 创建对象保存ApplicationServices startup中的app参数的ApplicationServices属性
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
            Startup.applicationService = app.ApplicationServices;
}
  1. 在startup中的Configure方法中记录下 app.ApplicationServices
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  Startup.applicationService = app.ApplicationServices;
}
  1. 获取对象
var machineService= Startup.applicationService.GetService<TestService>();

posted @ 2023-06-13 14:25  Hey,Coder!  阅读(22)  评论(0编辑  收藏  举报