Asp.net Core3.1使用Autofac

2021/10/1 17:12:18

本文主要是介绍Asp.net Core3.1使用Autofac,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

安装Autofac

 

 

Program文件中加入UseServiceProviderFactory

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

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

Startup 文件 ConfigureServices方法添加:

        services.Replace(
   ServiceDescriptor
       .Transient<IControllerActivator, ServiceBasedControllerActivator>()
);

添加ConfigureContainer方法

 public void ConfigureContainer(ContainerBuilder builder)
        {

            var assembly1= Assembly.GetAssembly(typeof(BaseService));
            var assembly2 = Assembly.GetExecutingAssembly();
            builder.RegisterAssemblyTypes(assembly1)
                .PublicOnly()
                .Where(r => r.Name.EndsWith("Service"))
                .AsImplementedInterfaces()
                .PropertiesAutowired()
                .InstancePerLifetimeScope();
            builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>();
            var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
        .Where(type => typeof(Microsoft.AspNetCore.Mvc.ControllerBase).IsAssignableFrom(type)).ToArray();
            builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();
        }

 



这篇关于Asp.net Core3.1使用Autofac的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程