net core 3.0 与Autofac

首先需要nuget引入包

using Autofac;
using Autofac.Extensions.DependencyInjection;

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;           
        }

        public IConfiguration Configuration { get; }
        public static IContainer AutofacContainer;

//定义autofac容器

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {           
            

            //注册数据库Gwglxs
            services.AddDbContext<GwglxsDbContext>(options =>
                        options.UseSqlServer(
                            Configuration.GetConnectionString("GwglxsConnection")
                        )//.UseLazyLoadingProxies()//懒加载,需要加载包:Microsoft.EntityFrameworkCore.Proxies
                    );

            services.AddMvcCore()
                .AddAuthorization();//认证服务.AddJsonFormatters()               

            services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority = "http://www.xxxx.com:5100";//授权服务器
                    options.RequireHttpsMetadata = false;

                    //options.Audience = "wyapicore";////"http://www.xxxx.cn:5211",//API数据提供中心
                    options.Audience = "wyapicore";////"http://www.xxxx.com:5211",//API数据提供中心
                });

            });

                        

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

            //services.AddControllers();//3.0
            services.AddControllersWithViews().AddControllersAsServices();//3.0
            services.AddRazorPages();//3.0
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddMemoryCache();//使用本地缓存必须添加
            services.AddSession();//使用Session
           

            services.AddSignalR();//使用 SignalR
            //
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            //add autofac
            ContainerBuilder containerbuilder = new ContainerBuilder();
            //将services中的服务填充到Autofac中
            containerbuilder.Populate(services);
            //型模块组件注册
            containerbuilder.RegisterModule<DefaultModuleRegister>();//<DefaultModuleRegister>();
            //创建容器
            AutofacContainer = containerbuilder.Build();
            //使用容器
            new AutofacServiceProvider(AutofacContainer);
        }

  //通过配置容器注册接口类

        public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterModule<DefaultModuleRegister>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHost host, Microsoft.Extensions.Hosting.IHostApplicationLifetime appLitetime)
        {
            //using (var container = host.Services.CreateScope())
            //{
            //    IPhone phone = container.ServiceProvider.GetService<IPhone>();
            //}

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();//????需要添加基础标识数据库架构之后才用与数据迁移
            }
            else
            {
                //app.UseExceptionHandler("/Home/Error");
                //the default hsts value is 30 days,you may want to change this for production scenarios,see https://aka.ms/aspnetcore-hsts.
                //app.UseHsts();

            }
            //app.UseHttpsRedirection();
            //app.UseSession();//app.UseSession();必须在app.UseHttpsRedirection();之后
            app.UseStaticFiles();
            app.UseCookiePolicy();           
            app.UseRouting();

            app.UseCors("default");//跨域管道
            //app.UseAuthentication();//认证管道
            app.UseAuthorization();//            

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();

                ////区域路由
                //endpoints.MapAreaControllerRoute(
                //    name: "areas",
                //    areaName:"areas",
                //    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                //endpoints.MapRazorPages();
            });

            //程序停止调用autofac函数
            appLitetime.ApplicationStopped.Register(() => { AutofacContainer.Dispose(); });
        }       

    }

/////////////////////////下面是接口及类的注册类////////////////////////////////

public class DefaultModuleRegister : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            ////注册当前程序集中以“Service”及“Repository”结尾的类,暴漏类实现的所有接口,生命周期为PerLifetimeScope

    //以“Service”及“Repository”结尾的类是利用发型实现的数据仓库的管理及业务处理的类和接口

            builder.RegisterAssemblyTypes(System.Reflection.Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(System.Reflection.Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces().InstancePerLifetimeScope();

        }

        public static Assembly GetAssembly(string assemblyName)
        {
            var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(AppContext.BaseDirectory + $"{assemblyName}.dll");
            return assembly;
        }

    }

猜你喜欢

转载自www.cnblogs.com/qingzhen/p/11712457.html