如下代码所示使用的是.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,有什么办法解决吗?
// 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名字不确定能不能用单例保存
以前是可以直接在构造函数中通过中使用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
回调的方式,生命周期貌似有问题,和正常获取的注入相互独立
你解决了,统样遇到了,实在不行只能用构造函数注入了
– 谁有我低调 4年前