Asp.NET Core with SimpleInjector 实例注册错误

Asp.NET Core with SimpleInjector Instance registration error

我正在尝试使用 SimpleInjector 编写 AspNet Api。 但是我在使用 SimpleInjector 时遇到了问题。当我在容器中注册类型后启动 AspNet 应用程序时,出现此错误:

Unhandled exception. System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Web.Services.WeatherForecastController Lifetime: Transient ImplementationType: Web.Services.WeatherForecastController': Unable to resolve service for type 'MediatR.IMediator' while attempting to activate 'Web.Services.WeatherForecastController'.) ---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: Web.Services.WeatherForecastController Lifetime: Transient ImplementationType: Web.Services.WeatherForecastController': Unable to resolve service for type 'MediatR.IMediator' while attempting to activate 'Web.Services.WeatherForecastController'. ---> System.InvalidOperationException: Unable to resolve service for type 'MediatR.IMediator' while attempting to activate 'Web.Services.WeatherForecastController'. at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)

我知道容器中缺少未注册的类型,但是我在实例化 Aspnet 服务器之前注册了中介器

 public class Program
    {
        public static async Task Main(string[] args)
        {
            var configuration = LoadConfiguration(args);
            var comp = new AspNetComponent(args);
            var container = new Container();
            container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
            container.Options.DefaultLifestyle = Lifestyle.Scoped;
            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
            container.Register<IMediator, Mediator>();
            comp.Configure(configuration, container);
            await comp.StartAsync(CancellationToken.None);
        }

在AspNetComponent.cs中:

 public static IHostBuilder CreateHostBuilder(
      string[] args, IConfiguration configuration, Container container)
        {
            Startup.UseContainer(container);
            return Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    webBuilder.UseUrls("https://0.0.0.0:8080");
                });
        }

还有我的Startup.csclass:

 public class Startup
    {
        private static Container _container;

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        internal static void UseContainer(Container container)
        {
            _container = container;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
                .AddApplicationPart(
                    Assembly.GetAssembly(typeof(WeatherForecastController)))
                .AddControllersAsServices();

            services.AddSimpleInjector(_container, options =>
            {
                options.AddAspNetCore()
                    .AddControllerActivation();
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseSimpleInjector(_container);
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }

我不知道是什么问题,我已经调试了将近 3 天。

我认为您的代码注册了两次控制器(一次在默认容器中,第二次在 .AddSimpleInjector 中)。默认容器排在第一位,它没有注册 Mediatr(我们只在 SimpleInjector 容器中注册过),因此在构造控制器时它会失败——它无法解析 IMediatr。只需删除注册控制器的第一个案例。

public void ConfigureServices(IServiceCollection services)
{
    // comment out first registration of services
    // we keep services.AddMvc() because it is required for simple injector container AddAspNetCore()
    services.AddMvc()
        .AddApplicationPart(Assembly.GetAssembly(typeof(WeatherForecastController)));
        //.AddControllersAsServices();

    // you are doing this in Program.cs
    var container = new Container();

    services.AddSimpleInjector(container, x =>
    {
        x.AddAspNetCore()
            .AddControllerActivation();
        // you are doing this in Program.cs
        x.Container.BuildMediator(Assembly.GetExecutingAssembly());
    });
}