[英]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使用
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
未应用于其容器。
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.