无法使用ASP.NET Core DI注入委托 [英] Can't inject a delegate using ASP.NET Core DI

查看:218
本文介绍了无法使用ASP.NET Core DI注入委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个像这样的MVC核心控制器:

Say I've a MVC Core Controller like this:

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

此外,我正在使用AutoFac解决注入.在添加委托注入时,对象注入可以完美地工作,从而产生一个ASP.NET Core异常,该异常表明无法注入Func<string>,因为没有组件可以使用这种类型进行注入.

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.

当我尝试使用AutoFac手动解决SomeController时,我得到了想要的行为.

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

是否有任何方法可以在不使用AutoFac来解析控制器的情况下支持这种情况?

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

推荐答案

默认情况下,控制器不是通过DI解析的,而是在DefaultControllerFactory左右构造的.

Controllers are not resolved via DI by default, they are constructed in the DefaultControllerFactory or so.

Microsoft.Extensions.DependencyInjection不支持命名组件,发现,自动注册,装饰器等.

Microsoft.Extensions.DependencyInjection doesn't support named components, discovery, auto registrations, decorators etc.

这意味着开箱即用的IoC是简单的,它为基本应用程序提供了DI的基础,并为集成第三方IoC容器(具有自动发现,装饰等高级功能)提供了简便的方法.他们需要处理IServiceCollection中的信息,并从Configure方法返回他们自己的IServiceProvider实现).

It's meant to be simple out of the box IoC and provide the base for DI for basic applications and offer easy way for 3rd party IoC containers (with advanced features such as auto discovery, decorators etc.) to be integrated (basically all they need is process the information in IServiceCollection and return their own implementation of IServiceProvider from Configure method).

标签帮助器,控制器和视图组件在这方面有所不同,因为它们具有自己的激活器(默认的一个使用激活实用程序,在某些时候会使用服务提供者).因此,AddControllersAsServices存在,因为它替换了DefaultControllerActivator(使用ActivationUtilities,请参见

Tag helpers, controllers and view components are different in this aspect as they have their own activators (the default one use activation utilities, which at some point further down the pipeline use the service provider). For that reasons AddControllersAsServices exists, because it replaces DefaultControllerActivator (which uses ActivationUtilities, see DefaultControllerActivator.cs) with ServiceBasedActivator (which uses IServiceProvider, see ServiceBasedControllerActivator).

另请参阅此相关答案,以获取有关如何通过DI解析控制器,标记助手和查看组件的详细信息.

Also see this related answer for details on how to resolve controllers, tag helpers and view components via DI.

var builder = services
    .AddMvc()
    .AddControllersAsServices() // this one for your case
    .AddViewComponentsAsServices()
    .AddTagHelpersAsServices();

这篇关于无法使用ASP.NET Core DI注入委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆