Adding Autofac JSON configuration to .NET core 6.0 using the new single file template

huangapple go评论137阅读模式
英文:

Adding Autofac JSON configuration to .NET core 6.0 using the new single file template

问题

I am trying to add Autofac to a .NET 6.0 web API and read Autofac components configuration from a JSON file.
我正在尝试将Autofac添加到.NET 6.0 Web API,并从JSON文件中读取Autofac组件配置。

Installed Autofac versions:
已安装的Autofac版本:

  1. Autofac.Configuration (6.0.0)
  2. Autofac.Extensions.DependancyInjection (8.0.0)

Installed .NET 6.0 versions:
已安装的.NET 6.0版本:

  1. Microsoft.AspNetCore.App 6.0.20
  2. Microsoft.NETCore.App 6.0.20

Just in case of doubt, this is the entire content of the Program.cs file (yes, no namespaces or class definition. Only a Program.cs file and no StartUp class or Startup.cs file)
以防有疑问,这是Program.cs文件的全部内容(是的,没有命名空间或类定义。只有一个Program.cs文件,没有StartUp类或Startup.cs文件)

  1. var configurationBuilder = new ConfigurationBuilder();
  2. configurationBuilder.AddJsonFile("autofac.json");
  3. var autoFacConfigurationModule = new ConfigurationModule(configurationBuilder.Build());
  4. var temp = new IpTablesDotNetSystem();
  5. var builder = WebApplication.CreateBuilder(args);
  6. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory((containerBuilder) =>
  7. {
  8. containerBuilder.RegisterModule(autoFacConfigurationModule);
  9. //containerBuilder.RegisterType<IpTablesDotNetSystem>().As<IIpTablesSystem>().SingleInstance();
  10. }
  11. ));
  12. // Add services to the container.
  13. builder.Services.AddControllers();
  14. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  15. builder.Services.AddEndpointsApiExplorer();
  16. builder.Services.AddSwaggerGen();
  17. var app = builder.Build();
  18. // Configure the HTTP request pipeline.
  19. if (app.Environment.IsDevelopment())
  20. {
  21. app.UseSwagger();
  22. app.UseSwaggerUI();
  23. }
  24. app.UseAuthorization();
  25. app.MapControllers();
  26. app.Run();

But I got exception like below:
但我得到了以下异常:

  1. System.InvalidOperationException: Unable to resolve service for type 'BSN.IpTables.Domain.IIpTablesSystem' while attempting to activate 'BSN.IpTables.Api.Controllers.HomeController'.
  2. at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
  3. at lambda_method364(Closure , IServiceProvider , Object[] )
  4. at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.<CreateActivator>b__0(ControllerContext controllerContext)
  5. at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
  6. at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
  7. at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
  8. --- End of stack trace from previous location ---
  9. at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
  10. at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
  11. at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
  12. at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
  13. at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
  14. at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
  15. at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
  16. at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

As you can see in the above code, if I uncomment
正如您在上述代码中所看到的,如果我取消注释:

  1. containerBuilder.RegisterType<IpTablesDotNetSystem>().As<IIpTablesSystem>().SingleInstance();

instead of RegisterModule all of project is correct working. but I need read configuration from files, and does not know how to do it?
而不是使用RegisterModule,整个项目都可以正常工作。但是我需要从文件中读取配置,但不知道如何做?

I've tried looking through the latest Autofac documentation, but I did not find anything to fit with .NET 6.0 code. I can't figure out how to use the Autofac configuration.
我已经尝试查看最新的Autofac文档,但没有找到与.NET 6.0代码匹配的内容。我无法弄清楚如何使用Autofac配置。

Code snippet from the Autofac website:
Autofac网站上的代码片段:

  1. // Add the configuration to the ConfigurationBuilder.
  2. var config = new ConfigurationBuilder();
  3. // config.AddJsonFile comes from Microsoft.Extensions.Configuration.Json
  4. // config.AddXmlFile comes from Microsoft.Extensions.Configuration.Xml
  5. config.AddJsonFile("autofac.json");
  6. // Register the ConfigurationModule with Autofac.
  7. var module = new ConfigurationModule(config.Build());
  8. var builder = new ContainerBuilder();
  9. builder.RegisterModule(module);

Autofac documentation:
Autofac文档:

https://autofac.readthedocs.io/en/latest/configuration/xml.html#quick-start

My complete project:
我的完整项目:

https://github.com/BSVN/IpTables.Api/pull/9


Update

My latest autofac.json file is like below:
我最新的autofac.json文件如下:

  1. {
  2. "components": [
  3. {
  4. "type": "BSN.IpTables.Data.IpTablesDotNetSystem, BSN.IpTables.Data",
  5. "services": [
  6. {
  7. "type": "BSN.IpTables.Domain.IIpTablesSystem, BSN.IpTables.Domain"
  8. }
  9. ],
  10. "instanceScope": "single-instance"
  11. }
  12. ]
  13. }
英文:

I am trying to add Autofac to a .NET 6.0 web API and read Autofac components configuration from a JSON file.
I'm using the latest ASP.NET Core Web API template that generates a single start-up Program.cs file.

Installed Autofac versions:

  1. Autofac.Configuration (6.0.0)
  2. Autofac.Extensions.DependancyInjection (8.0.0)

Installed .NET 6.0 versions:

  1. Microsoft.AspNetCore.App 6.0.20
  2. Microsoft.NETCore.App 6.0.20

Just in case of doubt, this is the entire content of the Program.cs file (yes, no namespaces or class definition. Only a Program.cs file and no StartUp class or Startup.cs file)

  1. var configurationBuilder = new ConfigurationBuilder();
  2. configurationBuilder.AddJsonFile("autofac.json");
  3. var autoFacConfigurationModule = new ConfigurationModule(configurationBuilder.Build());
  4. var temp = new IpTablesDotNetSystem();
  5. var builder = WebApplication.CreateBuilder(args);
  6. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory((containerBuilder) =>
  7. {
  8. containerBuilder.RegisterModule(autoFacConfigurationModule);
  9. //containerBuilder.RegisterType<IpTablesDotNetSystem>().As<IIpTablesSystem>().SingleInstance();
  10. }
  11. ));
  12. // Add services to the container.
  13. builder.Services.AddControllers();
  14. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  15. builder.Services.AddEndpointsApiExplorer();
  16. builder.Services.AddSwaggerGen();
  17. var app = builder.Build();
  18. // Configure the HTTP request pipeline.
  19. if (app.Environment.IsDevelopment())
  20. {
  21. app.UseSwagger();
  22. app.UseSwaggerUI();
  23. }
  24. app.UseAuthorization();
  25. app.MapControllers();
  26. app.Run();

But I got exception like below:

  1. System.InvalidOperationException: Unable to resolve service for type 'BSN.IpTables.Domain.IIpTablesSystem' while attempting to activate 'BSN.IpTables.Api.Controllers.HomeController'.
  2. at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
  3. at lambda_method364(Closure , IServiceProvider , Object[] )
  4. at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.<CreateActivator>b__0(ControllerContext controllerContext)
  5. at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
  6. at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
  7. at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
  8. --- End of stack trace from previous location ---
  9. at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
  10. at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
  11. at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
  12. at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
  13. at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
  14. at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
  15. at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
  16. at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

As you can see in the above code, if I uncomment

  1. containerBuilder.RegisterType<IpTablesDotNetSystem>().As<IIpTablesSystem>().SingleInstance();

instead of RegisterModule all of project is correct working. but I need read configuration from files, and does not know how to do it?

I've tried looking through the latest Autofac documentation, but I did not find anything to fit with .NET 6.0 code. I can't figure out how to use the Autofac configuration.

Code snippet from the Autofac website:

  1. // Add the configuration to the ConfigurationBuilder.
  2. var config = new ConfigurationBuilder();
  3. // config.AddJsonFile comes from Microsoft.Extensions.Configuration.Json
  4. // config.AddXmlFile comes from Microsoft.Extensions.Configuration.Xml
  5. config.AddJsonFile("autofac.json");
  6. // Register the ConfigurationModule with Autofac.
  7. var module = new ConfigurationModule(config.Build());
  8. var builder = new ContainerBuilder();
  9. builder.RegisterModule(module);

Autofac documentation:

https://autofac.readthedocs.io/en/latest/configuration/xml.html#quick-start

My complete project:

https://github.com/BSVN/IpTables.Api/pull/9


Update

My latest autofac.json file is like below:

  1. {
  2. "components": [
  3. {
  4. "type": "BSN.IpTables.Data.IpTablesDotNetSystem, BSN.IpTables.Data",
  5. "services": [
  6. {
  7. "type": "BSN.IpTables.Domain.IIpTablesSystem, BSN.IpTables.Domain"
  8. }
  9. ],
  10. "instanceScope": "single-instance"
  11. }
  12. ]
  13. }

答案1

得分: 0

You have to correct your JSON servics->services:

  1. {
  2. "components": [
  3. {
  4. "type": "BSN.IpTables.Data.IpTablesDotNetSystem, BSN.IpTables.Data",
  5. "services": [
  6. {
  7. "type": "BSN.IpTables.Domain.IIpTablesSystem, BSN.IpTables.Domain"
  8. }
  9. ]
  10. }
  11. ]
  12. }
英文:

You have to correct your JSON servics->services:

  1. {
  2. "components": [
  3. {
  4. "type": "BSN.IpTables.Data.IpTablesDotNetSystem, BSN.IpTables.Data",
  5. "services": [
  6. {
  7. "type": "BSN.IpTables.Domain.IIpTablesSystem, BSN.IpTables.Domain"
  8. }
  9. ]
  10. }
  11. ]
  12. }

huangapple
  • 本文由 发表于 2023年8月4日 21:54:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76836609.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定