Lars Thorén Lars Thorén - 4 years ago 164
C# Question

Injecting a logger with constructor dependencies

I'm trying to refactor some code to use .NET Core dependency injection via mapping services in startup.cs. I would like to inject an IRequestDatabaseLogger here instead of newing it up. However it requires the context in the constructor. How can I achieve this? Is it even possible without an DI framework or even then?

public class ActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var requestDatabaseLogger = new RequestDatabaseLogger(context);
long logId = requestDatabaseLogger.Log();

context.HttpContext.AddCurrentLogId(logId);

base.OnActionExecuting(context);
}
}

Answer Source

However it requires the context in the constructor.

Letting the construction of application components depend on runtime data is an anti-pattern, as described here. That article describes how to solve these problems in general.

In your case this probably means that your component should depend on ASP.NET Core's IHttpContextAccessor abstraction instead, which is a pattern described in the referenced article.

Alternatively, as described in the article, you can pass through the required runtime data to the logger using it's Log method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download