Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection of type Func<T> in ASP.NET Core

I am trying to inject a Func into a webapi controller using asp.net core 2.0.1 for my DataContext.

In my Startup.cs i have added;

services.AddTransient<Func<IDataContext>, Func<DataContext>>();

I then in my controller constructor pass this to my service;

private readonly ClientService _service;

public ClientController(Func<IDataContext> context)
{
     _service = new ClientService(context);
}

However, when I run the program and try to call an endpoint I am getting the error;

InvalidOperationException: Unable to resolve service for type 'System.Object' while attempting to activate 'System.Func`1[Data.EF.DataContext]'.

why is this please? and how can I resolve it.

like image 641
Matthew Flynn Avatar asked Mar 15 '18 06:03

Matthew Flynn


Video Answer


1 Answers

You are saying that Func<IDataContext> should be resolved as Func<DataContext>, but DI container has no idea how to construct Func<DataContext>, so you need to tell it explicitly:

// this assumes IDataContext is already registered in container
// if not - register it first
services.AddTransient<Func<IDataContext>>(cont => () => cont.GetService<IDataContext>());
like image 91
Evk Avatar answered Oct 07 '22 03:10

Evk