asp.net core3.0 mvc 用 autofac

好久没有写文章了,最近在用.net core3.0,一些开发中问题顺便记录;

1.首先nuget引入

Autofac

Autofac.Extensions.DependencyInjection

2.修改Program.cs 添加.UseServiceProviderFactory(new AutofacServiceProviderFactory())

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

3.修改Startup.cs

添加 services.AddControllersWithViews().AddControllersAsServices(); 

        public void ConfigureServices(IServiceCollection services)
        {
        services.AddControllersWithViews().AddControllersAsServices();
        }    

添加

        public void ConfigureContainer(ContainerBuilder builder)
        {
            // 在这里添加服务注册
        }


完成现在就可以在控制器中注入方法了。

posted @ 2019-09-27 21:33  橙子君123  阅读(1840)  评论(0编辑  收藏  举报