внедрение службы в промежуточное программное обеспечение в .net core 3.1 с неработоспособным autofac

#asp.net-core #autofac #asp.net-core-3.1 #asp.net-core-middleware

#asp.net-core #autofac #asp.net-core-3.1 #asp.net-core-промежуточное программное обеспечение

Вопрос:

Я обновил свое приложение с 2.2 .NET core до 3.1 .NET core. У меня есть одно промежуточное программное обеспечение, и я внедряю одну службу, которая работает в 2.2, но не работает в 3.1 .NET core с Autofac.

  public partial class TokenManagerMiddelware : IMiddleware
{
    #region Fields
    private readonly ITokenManagerService _tokenManagerService;
    #endregion

    #region Ctor
    public TokenManagerMiddelware(ITokenManagerService tokenManagerService)
    {
        _tokenManagerService = tokenManagerService;
    }
    #endregion
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
       // var _tokenManagerService = context.RequestServices.GetRequiredService<ITokenManagerService>();
        if (_tokenManagerService.IsCurrentActiveToken())
        {
            await next(context);
            return;
        }
        context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
    }
}
public static class TokenManagerMiddelwareExtention
{
    public static IApplicationBuilder UseTokenManagerMiddelware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<TokenManagerMiddelware>();
    }
}
  

Я также пробовал это

 var _tokenManagerService = context.RequestServices.GetRequiredService<ITokenManagerService>
  

Я получаю ошибку ниже в Autofac.

Исключение DependencyResolutionException: ни один из конструкторов не найден с помощью ‘Autofac.Core.Активаторы.Отражение.DefaultConstructorFinder ‘ on type’THub.Framework.Токен.TokenManagerMiddelware’ может быть вызван с доступными службами и параметрами: не удается разрешить параметр ‘THub.Services.TokemManager.ITokenManagerService tokenManagerService » конструктора»Void .ctor(THub.Services.TokemManager.ITokenManagerService)’. Autofac.Core.Активаторы.Отражение.ReflectionActivator.GetValidConstructorBindings(ConstructorInfo[] Доступные конструкторы, контекст IComponentContext, параметры IEnumerable)

Исключение DependencyResolutionException: при активации THub.Framework возникло исключение.Токен.TokenManagerMiddelware. Autofac.Core.Разрешение.Поиск экземпляра.Активировать(IEnumerable parameters, out object decoratorTarget)

Обновление 1 Program.cs

     using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace CoreApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}
  

Запуск.

     using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FirebaseAdmin;
using Google.Apis.Auth.OAuth2;
using Hangfire;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Serialization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Swashbuckle.AspNetCore.Swagger;
using Microsoft.OpenApi.Models;
using THub.Core.Caching;
using THub.Core.Data;
using THub.Data;
using THub.Framework.Infrastructure.Extensions;
using THub.Framework.Token;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.FileProviders;
using THub.Services.TokemManager;

namespace CoreApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
        {
            Configuration = configuration;
            _webHostEnvironment = webHostEnvironment;
        }

        public IConfiguration Configuration { get; }
        public IWebHostEnvironment _webHostEnvironment;

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<THubObjectContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")).UseLazyLoadingProxies()
                .EnableSensitiveDataLogging();
            });
            services.AddHttpClient();
            //Servies Regsters
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<THubObjectContext>()
                .AddDefaultTokenProviders();
            services.AddApiVersioning(options =>
            {
                options.ReportApiVersions = true;
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.DefaultApiVersion = new ApiVersion(1, 0);

            });
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();


            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            })

                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = false;
                    options.SaveToken = true;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = Configuration["Jwt:Issuer"],
                        ValidAudience = Configuration["Jwt:Issuer"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))

                    };
                });
            services.AddTransient<IDbContext, THubObjectContext>();
            services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
            //services.AddTransient<ITokenManagerService, TokenManagerService>();
            services.Configure<MongoDBDatabaseSetting>(Configuration.GetSection(nameof(MongoDBDatabaseSetting)));
            services.AddSingleton<IMongoDBDatabaseSetting>(sp =>
               sp.GetRequiredService<IOptions<MongoDBDatabaseSetting>>().Value);
            services.AddMvc().AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });
           
            services.AddTransient<TokenManagerMiddelware>();
            services.Configure<FormOptions>(x =>
            {
                x.ValueLengthLimit = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart
            });

            services.AddCors(options =>
            {
                options.AddPolicy("AllowCors",

                    builder =>
                    {
                        builder.AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                        //.AllowCredentials();
                        //builder.WithOrigins("http://localhost:4200")
                        //        .AllowAnyHeader()
                        //        .AllowAnyMethod();

                    });
            });
            //Hangfire service
            services.AddHangfire(option => option.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection"), new Hangfire.SqlServer.SqlServerStorageOptions
            {
                CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                QueuePollInterval = TimeSpan.Zero,
                UseRecommendedIsolationLevel = true,
                DisableGlobalLocks = true
            }));
            services.AddHangfireServer();


            services.AddSwaggerGen(options =>
            {

                options.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "Core API V1",
                    Version = "V1",
                    Contact = new OpenApiContact
                    {
                        Name = "Error Sheet",
                        Email = string.Empty,
                        Url = new Uri("http://xxxx.com/ErrorSheet.xlsx"),
                    }
                });
                options.AddSecurityDefinition("Bearer",
                    new OpenApiSecurityScheme
                    {
                        In = ParameterLocation.Header,
                        Description = "Please enter into field the word 'Bearer' following by space and JWT",
                        Name = "Authorization",
                        Type = SecuritySchemeType.ApiKey
                    });
                options.AddSecurityRequirement(new OpenApiSecurityRequirement() {
                             {
                                new OpenApiSecurityScheme
                                {
                                    Description = "Adds token to header",
                                    Name = "Authorization",
                                    Type = SecuritySchemeType.Http,
                                    In = ParameterLocation.Header,
                                    Scheme = "bearer",
                                    Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
                                },
                                new List<string>()
                            }
                    });

            });
            services.Configure<IdentityOptions>(options =>
            {
                //Password Setting // Setting Change deu to Management saying to make it easy.
                options.Password.RequireDigit = true; //Default true
                options.Password.RequireLowercase = true;//Default true
                options.Password.RequireNonAlphanumeric = true;//Default true
                options.Password.RequireUppercase = true;//Default true
                options.Password.RequiredLength = 8; ////Default 8
                options.Password.RequiredUniqueChars = 1;//Default 1

                // Lockout settings.  
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers = true;//Default true
                options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@ ";
                options.User.RequireUniqueEmail = true;


            });

            /*--------------------FCM Admin SDK---------------------------------- */


            var filePath = Configuration.GetSection("GoogleFirebase")["fileName"];
            var googleCredential = Path.Combine(_webHostEnvironment.ContentRootPath, filePath);
            var credential = GoogleCredential.FromFile(googleCredential);

            FirebaseApp.Create(new AppOptions()
            {
                
                Credential = credential,

            });
            /*-----------------------------Cloude Sdk------------------------------------------*/
            //var gcpPath = Configuration.GetSection("GoogleCloudStorage")["fileName"];
            //var gcpCredential = Path.Combine(_hostingEnvironment.ContentRootPath, gcpPath);
            //var gCPStorageCredential = GoogleCredential.FromFile(gcpCredential);
            //  var gcpStorage = StorageClient.Create(gCPStorageCredential);



            //Mini profiler

            services.AddMiniProfiler(options =>
            {
                options.RouteBasePath = "/profiler";
                //options.Storage = new StackExchange.Profiling.Data.ProfiledDbConnection(Configuration.GetConnectionString("DefaultConnection"));
                //(options.Storage as MemoryCacheStorage).CacheDuration = TimeSpan.FromDays(30);
                //options.Storage = new StackExchange.Profiling.Storage.SqlServerStorage(Configuration.GetConnectionString("DefaultConnection"),"MiniProfiler","MiniProfilerTimings","MiniProfilerClientTimings");
                //options.SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter();
            });
            //services.AddApplicationInsightsTelemetry();
            // Configure Compression level
            services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);

            // Add Response compression services
            services.AddResponseCompression(options =>
            {
                options.Providers.Add<GzipCompressionProvider>();
            });
            services.AddControllers();
            services.ConfigureApplicationServices(Configuration, _webHostEnvironment);

        }

        // 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.UseCors();
            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Upload")),
                RequestPath = "/Upload"
            });
            app.UseResponseCompression();
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "Core API V1");
            });
            app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseRouting();

            app.UseAuthorization();

            //app.UseMiddleware<TokenManagerMiddelware>();
            app.UseTokenManagerMiddelware();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

        }
    }
}
  

Комментарии:

1. Не могли бы вы предоставить свои Program.cs и Startup.cs, пожалуйста?

2. Я обновил свой код, пожалуйста, проверьте

3. Вы прокомментировали //services.AddTransient<ITokenManagerService, TokenManagerService>(); , чего не хватает. Это намеренно?

4. Я просто исправил, поэтому подумал, что это необходимо, почему я добавил, но не сработало, поэтому я прокомментировал. Здесь autofac контролирует все службы разрешения. Насколько я понимаю, сначала выполняется промежуточное программное обеспечение, а затем службы, поэтому его необходимая служба ITOkenManagerService. Но почему при работе в .net core 2.2 мой рабочий сервер все еще работает.