c# - ASP.NET Core 中 Func<T> 类型的依赖注入(inject)

标签 c# dependency-injection asp.net-core-2.0 asp.net-core-webapi

我正在尝试为我的 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/

相关文章:

c# - 将位图转换为 8bpp 灰度输出作为 c# 中的 8bpp 彩色索引

c# - 你能得到C#中哪个子进程调用了构造函数的信息吗?

java - Guice 的全局注入(inject)器

asp.net - 在asp.net core中根据权限隐藏菜单

c# - MVC6 - 如果(复选框勾选)则删除线

c# - 如果值匹配,则从另一个字符串数组获取字符串

dependency-injection - 统一: Implicit ResolvedParameter for unnamed registrations

symfony - 使用 Symfony DI 容器的原则 2

asp.net-core-2.0 - 在 Web API .NET Core 中接受 x-www-form-urlencoded

c# - .Net core 2 Web api 未将配置注入(inject)服务