1、Nuget引入程序包
2、指定Autofac工厂替换默认工厂,Program指定
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .UseServiceProviderFactory(new AutofacServiceProviderFactory());
3、在Startup类增加ConfigureContainer 方法
public void ConfigureContainer(ContainerBuilder builder) { builder.RegisterType<CustomServiceA>().As<ICustomServiceA>(); }
4、通过控制器构造函数注入,获取实例
public class FirstController : Controller { private readonly IConfiguration _Configuratin; public FirstController(IConfiguration configuration)//构造函数注入 { _Configuratin = configuration; } public IActionResult Index() { ViewBag.Conn= _Configuratin["connstr"]; return View(); } }
Nuget引入程序包