.net core autofac依赖注入简洁版

//依赖注入
        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");
                });
    }

 

上一篇:c-优化由Microsoft Visual Studio编译器生成的程序集


下一篇:2020年最新 C# .net 面试题,月薪20K+中高级/架构师必看(7)