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

人盡茶涼 提交于 2019-12-23 23:05:46

问题


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?


回答1:


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)));
}



回答2:


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);
    }
}


来源:https://stackoverflow.com/questions/36548595/how-di-container-knows-what-constructors-need-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!