Dmitry Tabakerov Dmitry Tabakerov - 1 year ago 100
C# Question

How DI container knows what Constructors need (ASP.NET Core)?

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?

Answer Source

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)));
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download