Can't inject a delegate using ASP.NET Core DI

Viewed 3059

Say I've a MVC Core Controller like this:

public class SomeController
{
     public SomeController(IConfiguration appConfig, Func<string> someDelegate)
     {
     }
}

Also, I'm using AutoFac to resolve injections. Object injections are working flawlessly while adding a delegate injection produces an ASP.NET Core exception which tells that Func<string> can't be injected because there's no component to inject with such type.

When I try to manually resolve SomeController using AutoFac I get the desired behavior.

Is there any way to support this scenario without using AutoFac to resolve controllers?

2 Answers

I was just run into this issue myself so I thought I would share for future reference as I had one case where I wanted to resolve a delegate but including an additional library seemed like overkill.

Given the following defintions:

public interface ISomething { /*...*/ };
public interface ISomeService { /*...*/ }

public class SomeService : ISomeService { /*...*/ }

public class Something
{
    public Something(ISomeService service, string key) { /*...*/ }
}

// I prefer using a delegate for readability but you
// don't have to use one
public delegate ISomething CreateSomething(string key);

The delegate can be registered like this:

var builder = services
    .AddSingleton<ISomeService, SomeService>()
    .AddTrasient<CreateSomething>(provider => key => new Something(provider.GetRequiredService<ISomeService>(), key));
Related