使用新的单文件模板将 Autofac Json 配置添加到 .NET core 6.0

问题描述 投票:0回答:1

我正在尝试将 Autofac 添加到 .NET 6.0 Web API 并从 JSON 文件读取 Autofac 组件配置。 我正在使用最新的 ASP.NET Core Web API 模板,该模板生成单个启动 Program.cs 文件。

已安装的 Autofac 版本:

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

已安装的.Net 6.0版本:

Microsoft.AspNetCore.App 6.0.20
Microsoft.NETCore.App 6.0.20

以防万一,这是 Program.cs 文件的全部内容(是的,没有命名空间或类定义。只有 Program.cs 文件,没有 StartUp 类或 Startup.cs 文件) )

var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("autofac.json");
var autoFacConfigurationModule = new ConfigurationModule(configurationBuilder.Build());
var temp = new IpTablesDotNetSystem();

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory((containerBuilder) =>
{
    containerBuilder.RegisterModule(autoFacConfigurationModule);
    //containerBuilder.RegisterType<IpTablesDotNetSystem>().As<IIpTablesSystem>().SingleInstance();
}
));

// Add services to the container.
builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();

但是我遇到了如下异常:

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

正如你在上面的代码中看到的,如果我取消注释

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

而不是

RegisterModule
所有项目都正常工作。但我需要从文件中读取配置,并且不知道该怎么做?

我尝试查看最新的 Autofac 文档,但没有找到任何适合 .NET 6.0 代码的内容。我不知道如何使用 Autofac 配置。

来自 Autofac 网站的代码片段:

// Add the configuration to the ConfigurationBuilder.
var config = new ConfigurationBuilder();

// config.AddJsonFile comes from Microsoft.Extensions.Configuration.Json
// config.AddXmlFile comes from Microsoft.Extensions.Configuration.Xml
config.AddJsonFile("autofac.json");

// Register the ConfigurationModule with Autofac.
var module = new ConfigurationModule(config.Build());
var builder = new ContainerBuilder();
builder.RegisterModule(module);

Autofac 文档:

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

我的完整项目:

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


更新

我最新的autofac.json文件如下:

{
  "components": [
    {
      "type": "BSN.IpTables.Data.IpTablesDotNetSystem, BSN.IpTables.Data",
      "services": [
        {
          "type": "BSN.IpTables.Domain.IIpTablesSystem, BSN.IpTables.Domain"
        }
      ],
      "instanceScope": "single-instance"
    }
  ]
}
c# asp.net-core .net-6.0 autofac autofac-configuration
1个回答
0
投票

您必须更正您的 JSON

servics
->
services
:

{
  "components": [
    {
      "type": "BSN.IpTables.Data.IpTablesDotNetSystem, BSN.IpTables.Data",
      "services": [
        {
          "type": "BSN.IpTables.Domain.IIpTablesSystem, BSN.IpTables.Domain"
        }
      ]
    }
  ]
}
© www.soinside.com 2019 - 2024. All rights reserved.