DI容器如何知道构造函数需要什么(ASP.NET Core)?

编程入门 行业动态 更新时间:2024-10-17 23:34:35
本文介绍了DI容器如何知道构造函数需要什么(ASP.NET Core)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经阅读了很多关于什么是DI以及如何使用DI(与ASP.NET Core相关)的文档。据我了解,当框架为我实例化某个控制器时,它以某种方式知道该控制器的类需要传递给构造函数的内容。是反射还是什么?有人可以告诉我在ASP.NET Core GitHub上的哪里可以看到它吗?

I've read a lot of docs on what is DI and how to use it (related to ASP.NET Core). As I understand when framework instantiates some controller for me it somehow knows what that controller's class need to pass to constructor. Is it reflection or something? Can someone show me where can I see it on ASP.NET Core GitHub sources?

推荐答案

ASP的构造函数选择行为。当前RC1上的NET Core DI相当复杂。过去,它仅支持具有单个构造函数的类型,该构造函数为很好的默认值。但是,在RC1中,它接受具有多个构造函数的类型。尽管如此,它的行为还是很奇怪,在测试期间,我没有设法让DI容器为我创建一个具有多个构造函数的组件。

The constructor selection behavior of the ASP.NET Core DI on the current RC1 is rather complicated. In the past it only supported types with a single constructor, which is a very good default. In RC1 however, it accepts types with multiple constructors. Still, its behavior is very weird, and during testing, I didn't manage to let the DI container to create a component for me that had multiple constructors.

涵盖了构造函数的选择,构造函数参数的分析全部使用反射完成,并且构建了一个表达式树,最终将其编译为委托。代码很简单,就像这

Under the covers the selection of the constructor and the analysis of the constructors parameters is all done using reflection and an expression tree is built up and eventually compiled down to a delegate. The code is as simple as this:

public Expression Build(Expression provider) { var parameters = _constructorInfo.GetParameters(); return Expression.New( _constructorInfo, _parameterCallSites.Select((callSite, index) => Expression.Convert( callSite.Build(provider), parameters[index].ParameterType))); }

更多推荐

DI容器如何知道构造函数需要什么(ASP.NET Core)?

本文发布于:2023-11-14 04:16:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586187.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:容器   函数   DI   Core   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!