Last post Mar 24, 2016 10:06 AM by EastCoder
Mar 24, 2016 08:06 AM|EastCoder|LINK
as we all know, The DefaultHttpControllerActivator(implement
IHttpControllerActivator) is used to create an instance of the web-api controller.
The part code as below is the source of the DefaultHttpControllerActivator class:
private static IHttpController GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, out Func<IHttpController> activator)
IHttpController httpController = (IHttpController)request.GetDependencyScope().GetService(controllerType);
if (httpController != null)
activator = null;
activator = TypeActivator.Create<IHttpController>(controllerType);
actually, there are 2 steps executed as above.
step1: if the IOC container isn't empty and can return an instance of the controller, then return.
Step2:If not, TypeActivator is used to do that.
So my question is that how the TypeActivator builds an instance? what's the implementation inside? maybe someone said that the Reflector is used! but i'm not sure, due to there is no keyword like "Activctor.CreateInstance()" used!
below is the source of the TypeActivator class:
public static Func<TBase> Create<TBase>(Type instanceType) where TBase : class
NewExpression body = Expression.New(instanceType);
return Expression.Lambda<Func<TBase>>(body, new ParameterExpression).Compile();
who can explain to me for this question, thanks for you in advanced!
Mar 24, 2016 08:26 AM|PatriceSc|LINK
See https://msdn.microsoft.com/en-us/library/bb397951.aspx. This is how LINQ to EF for example; works that is you pass C# code as parameter and this code can be then analyzed and converted
to the corresponding SQL statement.
But you can also create this kind of "expressino tree" programmtically. This is what the code abobe does. It creates and compiles a new TheType() expression so later calling that will just return a new instance for this type.
Mar 24, 2016 10:06 AM|EastCoder|LINK
thanks for your helpful link, this is a new topic for me to learn.