DI容器如何知道构造函数需要什么(ASP.NET Core)? [英] How DI container knows what Constructors need (ASP.NET Core)?

查看:67
本文介绍了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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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