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.
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>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With