[英]How to Register ILogger(Microsoft.Extensions.Logging) with DI usinq autofac .net framework
I use ILogger from Microsoft.Extensions.Logging in a .net framework project.我在 .net 框架项目中使用 Microsoft.Extensions.Logging 的 ILogger。 Now I want to register the ILogger in the container but i cant.All the answers are about .net core.
现在我想在容器中注册 ILogger 但我不能。所有的答案都是关于 .net 核心。 i try
我试试
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);
also my class is我的 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;
}
}
The di is correct because other services have injected correct. di 是正确的,因为其他服务已正确注入。 When i include the logger in constructor i get the message An error occurred when trying to create a controller of type 'TestController '.
当我在构造函数中包含记录器时,我收到消息尝试创建“TestController”类型的 controller 时发生错误。 Make sure that the controller has a parameterless public constructor.
确保 controller 具有无参数的公共构造函数。
Since trying to integraten with those extensions, consider populating the service collection is expected and populating the builder once everything is registered,由于尝试与这些扩展集成,请考虑填充服务集合并在注册所有内容后填充构建器,
Example from docs来自文档的示例
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);
ILogger is great in.Net core, but in.Net framework, I'd suggest using ILog (log4net). ILogger 在.Net 核心中很棒,但在.Net 框架中,我建议使用 ILog (log4net)。
Implement log4net in a windows service using dependency injection 使用依赖注入在 windows 服务中实现 log4net
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.