首页 新闻 会员 周边 捐助

.net core3.1中使用autofac怎么得到IContainer?

0
悬赏园豆:5 [待解决问题]

如下代码所示使用的是.net core3.1使用的是Autofac框架来做依赖注入

Program.cs  

public static void Main(string[] args)
        {
            //启动 kestrel  本地调试端口默认配置在 launchSettings.json
            CreateHostBuilder(args).Build().Run();

        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureLogging(loggingBuider =>
            {
                //配置Log4为log组件
                loggingBuider.AddLog4Net("Config\\Log4net.config");//使用相对路径
            })
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())//设置服务提供者为autofac
            .ConfigureWebHostDefaults(webBuilder =>
            {
                // 设置Startup为启动类型 
                webBuilder.UseStartup<Startup>();
            });

Startup.cs

复制代码
      public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            
            services.AddControllers(
                options =>
                {
                    //注册全局异常处理
                    options.Filters.Add<ApiExceptionFilterAttribute>();
                });
            //通过option获取服务
            services.Configure<AppSetting>(Configuration);
        }

        /// <summary>
        /// 使用Autofac在这里注册服务
        /// </summary>
        /// <param name="containerBuilder"></param>
        public void ConfigureContainer(ContainerBuilder containerBuilder)
        {
            containerBuilder.RegisterModule<AutofacRegister>();
            //IContainer container= containerBuilder.Build();  //这里不能Build 不然会报错
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
复制代码

配置好了也能正常使用,但是现在有个问题,之前是.net framework的代码,准备迁移到.net core3.1,很多地方不是使用构造函数注入的方式获取服务的,如

var testService= container.Resolve<ITestService>();

container 是使用的Autofac.IContainer对象,通过

containerBuilder.Build()获取得到的一个对象,然后使用一个静态的对象保存的,现在到了.net core3.1中拿不到
IContainer,有什么办法解决吗?
猴哥aiyy的主页 猴哥aiyy | 初学一级 | 园豆:3
提问于:2020-06-25 21:50

你解决了,统样遇到了,实在不行只能用构造函数注入了

谁有我低调 4年前
< >
分享
所有回答(2)
2
  // Configure is where you add middleware. This is called after
  // ConfigureContainer. You can use IApplicationBuilder.ApplicationServices
  // here if you need to resolve things from the container.
  public void Configure(
    IApplicationBuilder app,
    ILoggerFactory loggerFactory)
  {
    // If, for some reason, you need a reference to the built container, you
    // can use the convenience extension method GetAutofacRoot.
    this.AutofacContainer = app.ApplicationServices.GetAutofacRoot();

    loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    app.UseMvc();
  }

在autofac官网看到这个,AutofacContainer是ILifetimeScope类型的,IContainer继承自ILifetimeScope,看ILifetimeScope名字不确定能不能用单例保存

猴哥aiyy | 园豆:3 (初学一级) | 2020-06-25 23:44
0

以前是可以直接在构造函数中通过中使用autofac IContainer,.net core3.1现在想在构造函数中获取ico容器的话,变为了ILifetimeScope。

    public HangfireCrawlerSaleHouse(ILogger<HangfireCrawlerJob> logger,
                                                          QFangDbContext qFangDbContext,
                                                          ILifetimeScope lifetimeScope)

{
this.lifetimeScope.Resolve<T>().......
}

也可以通过回调
//aotuofac服务注册完成回调
builder.RegisterBuildCallback(lifetimeScope =>
{
ServiceProviderInstance.Container = lifetimeScope as IContainer;
});

IContainer继承自ILifetimeScope 所以This cast is valid because IContainer : ILifetimeScope

跟着阿笨一起玩.NET | 园豆:9 (初学一级) | 2020-10-02 12:47

回调的方式,生命周期貌似有问题,和正常获取的注入相互独立

支持(0) 反对(0) 笑看代码的猫 | 园豆:200 (初学一级) | 2021-01-25 15:04
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册