简体   繁体   English

无法让 Lamar (IOC) 解决 .NET Core 3.1 中的 API 控制器依赖项

[英]Can't get Lamar (IOC) to resolve API Controller Dependencies in .NET Core 3.1

I am getting an error when trying to call the controller below using Lamar to resolve the dependencies at runtime.尝试使用 Lamar 调用下面的控制器以在运行时解决依赖关系时出现错误。

I have tried .AddControllersAsServices() and without and still get the same result.我已经尝试过.AddControllersAsServices()并且没有并且仍然得到相同的结果。

Using使用

  • ASP.NET Core: 3.1 ASP.NET 核心:3.1
  • Lamar拉马尔

Container.GetInstance<IDataAccess>() works inside the watch window but will not resolve at runtime Container.GetInstance<IDataAccess>()在监视窗口内工作,但不会在运行时解析

Container.WhatDoIHave() also shows that the dependency is there Container.WhatDoIHave()也表明依赖在那里

Question?题?
What am I missing in Lamar configuration to resolve the controllers?我在 Lamar 配置中缺少什么来解析控制器?

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private readonly IDataAccess _dataAccess;
    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(IDataAccess dataAccess, ILogger<WeatherForecastController> logger)
    {
        _dataAccess = dataAccess;
    }

    [HttpGet]
    public IEnumerable<string> Get()
    {
        return _dataAccess.GetAll();
    }
}

Startup.cs启动文件


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

    public IConfiguration Configuration { get; }

    public IContainer Container { get; private set; }

    public void ConfigureContainer(ServiceRegistry services)
    {
        Container = new Container(cfg =>
        {
            cfg.Scan(scanner =>
            {
                scanner.AssembliesAndExecutablesFromApplicationBaseDirectory(a =>
                    a.FullName.Contains("Test3.1"));
                scanner.WithDefaultConventions();
                scanner.SingleImplementationsOfInterface();
            });
        });

        services
            .AddControllers(options =>
            {
                // Disable automatic fallback to JSON
                options.ReturnHttpNotAcceptable = true;

                // Honor browser's Accept header (e.g. Chrome)
                options.RespectBrowserAcceptHeader = true;
            })
            .AddControllersAsServices();

        services.AddMvc()
            .AddControllersAsServices();

        Container.WhatDidIScan();
        Container.WhatDoIHave();

        Console.Write("Container Instantiated");
    }

    // 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.UseDefaultFiles();
        app.UseStaticFiles();
        app.UseRouting();

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

Program.cs程序.cs


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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseLamar()
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIISIntegration()
                    .UseStartup<Startup>();

            });
}

An unhandled exception occurred while processing the request.处理请求时发生未处理的异常。

LamarException: Cannot build registered instance weatherForecastController of 'Test3._1.Controllers.WeatherForecastController': Cannot fill the dependencies of any of the public constructors Available constructors:new WeatherForecastController(IDataAccess dataAccess, ILogger<Test3._1.Controllers.WeatherForecastController> logger) * IDataAccess is not registered within this container and cannot be auto discovered by any missing family policy LamarException:无法构建“Test3._1.Controllers.WeatherForecastController”的注册实例weatherForecastController:无法填充任何公共构造函数的依赖项可用构造函数:new WeatherForecastController(IDataAccess dataAccess, ILogger<Test3._1.Controllers.WeatherForecastController> logger) * IDataAccess 未在此容器中注册,并且无法被任何缺失的家族策略自动发现

The error message indicates that the container can't resolve the controller's dependencies.该错误消息表明容器无法解析控制器的依赖项。 Make sure those dependencies are registered with the container so it knows how to resolve them when activating controllers.确保这些依赖项已在容器中注册,以便在激活控制器时知道如何解决它们。

This is because separate containers are being configured in Startup and the one used by the framework is unaware of IDataAccess as the Scan was not applied to its container.这是因为在Startup中配置了单独的容器,框架使用的容器不知道IDataAccess因为Scan未应用于其容器。

Reference Lamar - Integration with ASP.Net Core参考Lamar - 与 ASP.Net Core 集成

public class Startup {

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

    public IConfiguration Configuration { get; }

    //REMOVED IContainer. It is not needed

    public void ConfigureContainer(ServiceRegistry services) {

        //Apply scan to the registry used by framework so container is aware of types.
        services.Scan(scanner => {
            scanner.AssembliesAndExecutablesFromApplicationBaseDirectory(a =>
                a.FullName.Contains("Test3.1"));
            scanner.WithDefaultConventions();
            scanner.SingleImplementationsOfInterface();
        });

        services
            .AddControllers(options => {
                // Disable automatic fallback to JSON
                options.ReturnHttpNotAcceptable = true;
                // Honor browser's Accept header (e.g. Chrome)
                options.RespectBrowserAcceptHeader = true;
            })
            .AddControllersAsServices();

        services.AddMvc()
            .AddControllersAsServices();

        services.WhatDidIScan();
        services.WhatDoIHave();

        Console.Write("Container Instantiated");
    }

    //...omitted for brevity
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法解析Web Api Controller中的依赖项 - Can't resolve dependencies in Web Api Controller StructureMap -&gt; Lamar .NET Core 3.1 服务创建不起作用 - StructureMap -> Lamar .NET Core 3.1 service creation not working 如何在 .Net Core 3.1 Web API 控制器中获取声明? - How to get claims in .Net Core 3.1 Web API Controller? 如何解决.net core 中动态控制器的依赖关系? - How to resolve dependencies for dynamic controller in .net core? ASP.Net Core 3.1 WEB API - Controller 方法不返回正确的 Z0ECD11C1D7A287401F814A8 - ASP.Net Core 3.1 WEB API - Controller method doesn't return correct JSON Autofac 作为 AWS 中的 IoC 容器 Lambda 无服务器 ASP.NET Core 3.1 Web ZDB974238714CA8DE64FZACE7 - Autofac as IoC container in AWS Lambda Serverless ASP.NET Core 3.1 Web API 无法解析.Net Core 中的符号“FirstOrDefaultAsync” Web API - Can't resolve symbol "FirstOrDefaultAsync" in .Net Core Web API .net 核心 3.1 中 [RoutePrefix("api/{controller})] 的替代方案是什么? - What is alternate for [RoutePrefix("api/{controller})] in .net core 3.1? 使用 .NET Core 3.1 中的 TestServer 加载额外的 controller Web ZDB974238714CA8DE634A7CE1D0Z - Load additional controller using TestServer in .NET Core 3.1 Web API 如何在 api mvc 项目 net core 3.1 中向 controller 添加操作 - How to add action to controller in api mvc project net core 3.1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM