How to instantiate an ILoggerFactory without using Dependency Injection?

Viewed 2018

I have an existing class that needs a parameterless constructor. I want to log an error and some other data from within it. Everywhere else in my app I put the ILoggerFactory in my constructor and DI takes care of it and thus I can log and such. I can not do that in this case because of the requirement of the parameterless constructor.

Can I create a instance of the ILoggerFactory or any other class I have put into the Dependency Injection stream from my Startup class?

2 Answers

In Configure (in Startup.cs) you get IApplicationBuilder passed in, which has an ApplicationServices property (IServiceProvider).

You can easily do something like

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

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

and then later, somewhere totally unrelated, do

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

    // Do something with service
}

It's a horrible anti-pattern, and you should never do this, though.

Shamelessly stolen from https://github.com/aspnet/DependencyInjection/issues/294 (so that it would be here for posterity).

Autofac supports property Injection which allows you to inject a Logger after the object has been resolved from the container. It's configured using .PropertiesAutowired in the builder code.

Related