c# - 如何在不使用依赖注入(inject)的情况下实例化 ILoggerFactory?

标签 c# dependency-injection .net-core

我有一个需要无参数构造函数的现有类。我想记录一个错误和其中的一些其他数据。在我的应用程序的其他任何地方,我都将 ILoggerFactory 放在我的构造函数中,DI 会处理它,因此我可以记录等等。由于无参数构造函数的要求,在这种情况下我不能这样做。

我可以创建 ILoggerFactory 的实例或我从 Startup 类放入依赖注入(inject)流中的任何其他类吗?

最佳答案

在 Configure 中(在 Startup.cs 中),您将传入 IApplicationBuilder,它具有 ApplicationServices 属性 (IServiceProvider)。

你可以很容易地做类似的事情

public void Configure(IApplicationBuilder app)
{
    GetMeSomeServiceLocator.Instance = app.ApplicationServices;
}

public static class GetMeSomeServiceLocator
{
    public static IServiceProvider Instance { get; set; }
}

然后,在完全不相关的地方,做

public void SomeRandomMethod()
{
    var service = GetMeSomeServiceLocator.Instance.GetService<MyAwesomeService>();

    // Do something with service
}

这是一个可怕的反模式,但是你永远不应该这样做。

无耻地盗自https://github.com/aspnet/DependencyInjection/issues/294 (这样它就会留在这里供后代使用)。

关于c# - 如何在不使用依赖注入(inject)的情况下实例化 ILoggerFactory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46383377/

相关文章:

c# - Entity Framework : Object is null but the foreign key isn't

c# - 高性能事件日志

c# - ASP.NET Core Entity Framework 代码到数据库脚手架无法识别 Id 属性或 [Key] 注释

c# - Ninject 基于约定的绑定(bind)将在运行时解析

c# - 进程 'C:\hostedtoolcache\windows\dotnet\dotnet.exe' 失败,退出代码 1

c# - .Net 7 隔离进程中的服务总线触发 Azure Function - 处理死信队列

c# - 如何使用 moq 和 mspec(BDD 风格)比较两个对象列表

c# - await client.GetStringAsync 无一异常(exception)退出

android - Dagger 2 : error: [Dagger/MissingBinding] cannot solve this one

c# - 为什么使用 IKernel 而不是 IWindsorContainer?