我正在尝试为我的 DataContext 使用 asp.net core 2.0.1 将 Func 注入(inject)到 webapi Controller 中。
在我的 Startup.cs 中添加了;
services.AddTransient<Func<IDataContext>, Func<DataContext>>();
然后我在我的 Controller 构造函数中将它传递给我的服务;
private readonly ClientService _service;
public ClientController(Func<IDataContext> context)
{
_service = new ClientService(context);
}
但是,当我运行程序并尝试调用端点时,我收到了错误;
InvalidOperationException: Unable to resolve service for type 'System.Object' while attempting to activate 'System.Func`1[Data.EF.DataContext]'.
请问这是为什么?我该如何解决。
最佳答案
你是说 Func<IDataContext>
应解析为 Func<DataContext>
, 但 DI 容器不知道如何构造 Func<DataContext>
,所以你需要明确地告诉它:
// this assumes IDataContext is already registered in container
// if not - register it first
services.AddTransient<Func<IDataContext>>(cont => () => cont.GetService<IDataContext>());
关于c# - ASP.NET Core 中 Func<T> 类型的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49292784/