Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 510
Dmitry Tabakerov Avatar asked Dec 19 '22 17:12

Dmitry Tabakerov


2 Answers

You can start looking here on GitHub.

In a nut shell it is using reflection to inspect the public constructors of the type and their parameters.

var constructors = implementationType.GetTypeInfo()
    .DeclaredConstructors
    .Where(constructor => constructor.IsPublic)
    .ToArray();

It sorts the the constructors based on parameter length and then selects the best one.

This snippet looks for the best constructor to call for the type being instantiated.

private ServiceCallSite CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType,
    CallSiteChain callSiteChain)
{
    try
    {
        callSiteChain.Add(serviceType, implementationType);
        var constructors = implementationType.GetTypeInfo()
            .DeclaredConstructors
            .Where(constructor => constructor.IsPublic)
            .ToArray();

        ServiceCallSite[] parameterCallSites = null;

        if (constructors.Length == 0)
        {
            throw new InvalidOperationException(Resources.FormatNoConstructorMatch(implementationType));
        }
        else if (constructors.Length == 1)
        {
            var constructor = constructors[0];
            var parameters = constructor.GetParameters();
            if (parameters.Length == 0)
            {
                return new ConstructorCallSite(lifetime, serviceType, constructor);
            }

            parameterCallSites = CreateArgumentCallSites(
                serviceType,
                implementationType,
                callSiteChain,
                parameters,
                throwIfCallSiteNotFound: true);

            return new ConstructorCallSite(lifetime, serviceType, constructor, parameterCallSites);
        }

        Array.Sort(constructors,
            (a, b) => b.GetParameters().Length.CompareTo(a.GetParameters().Length));

        ConstructorInfo bestConstructor = null;
        HashSet<Type> bestConstructorParameterTypes = null;
        for (var i = 0; i < constructors.Length; i++)
        {
            var parameters = constructors[i].GetParameters();

            var currentParameterCallSites = CreateArgumentCallSites(
                serviceType,
                implementationType,
                callSiteChain,
                parameters,
                throwIfCallSiteNotFound: false);

            if (currentParameterCallSites != null)
            {
                if (bestConstructor == null)
                {
                    bestConstructor = constructors[i];
                    parameterCallSites = currentParameterCallSites;
                }
                else
                {
                    // Since we're visiting constructors in decreasing order of number of parameters,
                    // we'll only see ambiguities or supersets once we've seen a 'bestConstructor'.

                    if (bestConstructorParameterTypes == null)
                    {
                        bestConstructorParameterTypes = new HashSet<Type>(
                            bestConstructor.GetParameters().Select(p => p.ParameterType));
                    }

                    if (!bestConstructorParameterTypes.IsSupersetOf(parameters.Select(p => p.ParameterType)))
                    {
                        // Ambiguous match exception
                        var message = string.Join(
                            Environment.NewLine,
                            Resources.FormatAmbiguousConstructorException(implementationType),
                            bestConstructor,
                            constructors[i]);
                        throw new InvalidOperationException(message);
                    }
                }
            }
        }

        if (bestConstructor == null)
        {
            throw new InvalidOperationException(
                Resources.FormatUnableToActivateTypeException(implementationType));
        }
        else
        {
            Debug.Assert(parameterCallSites != null);
            return new ConstructorCallSite(lifetime, serviceType, bestConstructor, parameterCallSites);
        }
    }
    finally
    {
        callSiteChain.Remove(serviceType);
    }
}
like image 121
Nkosi Avatar answered Mar 29 '23 23:03

Nkosi


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)));
}
like image 35
Steven Avatar answered Mar 29 '23 23:03

Steven