gpt4 book ai didi

c# - 如何使用 DI usinq autofac .net 框架注册 ILogger(Microsoft.Extensions.Logging)

转载 作者:行者123 更新时间:2023-12-04 17:31:53 27 4
gpt4 key购买 nike

我在 .net 框架项目中使用来自 Microsoft.Extensions.Logging 的 ILogger。
现在我想在容器中注册 ILogger 但我不能。所有答案都是关于 .net core 的。
我试试

var builder = new ContainerBuilder();

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

//first try
builder.RegisterGeneric(typeof(Logger<>)).As(typeof(ILogger<>));
IServiceCollection services = new ServiceCollection();

//second try
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
IContainer container = builder.Build();

httpConfig.DependencyResolver = new AutofacWebApiDependencyResolver(container);

我的类(class)也是
public class TestController : ApiController
{
private readonly ILogger<TestController > _logger;
private readonly IService _service;

public TestController (IService service, ILogger<TestController > logger)
{
_service = service;
_logger = logger;
}
}

di 是正确的,因为其他服务已正确注入(inject)。
当我在构造函数中包含记录器时,我收到消息
尝试创建类型为“TestController”的 Controller 时发生错误。确保 Controller 具有无参数的公共(public)构造函数。

最佳答案

由于尝试与这些扩展集成,请考虑填充预期的服务集合并在注册完所有内容后填充构建器,

来自文档的示例

var builder = new ContainerBuilder();

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

IServiceCollection services = new ServiceCollection();

// The Microsoft.Extensions.Logging package provides this one-liner
// to add logging services.
services.AddLogging();

// Once you've registered everything in the ServiceCollection, call
// Populate to bring those registrations into Autofac. This is
// just like a foreach over the list of things in the collection
// to add them to Autofac.
builder.Populate(services);

IContainer container = builder.Build();

httpConfig.DependencyResolver = new AutofacWebApiDependencyResolver(container);

引用 Autofac: .Net Core Integration

关于c# - 如何使用 DI usinq autofac .net 框架注册 ILogger(Microsoft.Extensions.Logging),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58819370/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com