//依赖注入 public void ConfigureContainer(ContainerBuilder builder) { Assembly iserAss = Assembly.Load("Interface"); Assembly serAss = Assembly.Load("Service"); //创建serAss中的所有类的instance以此类的实现接口存储 builder.RegisterAssemblyTypes(iserAss, serAss).AsImplementedInterfaces().PropertiesAutowired();//支持构造方式注入和属性方式注入,不加PropertiesAutowired则只支持构造方式 //注入到控制器 var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes() .Where(type => typeof(Controller).IsAssignableFrom(type)).ToArray(); builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired(); }
public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, configBuilder) => { //configBuilder // .AddJsonFile("Config/Mongo.json") // .AddJsonFile("Config/SqlConn.json");//注入json文件 }) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>().UseUrls("http://*:8080"); }); }
原文:https://www.cnblogs.com/jianghaidong/p/14710674.html