IControllerActivator has two implementation: DefaultControllerActivator and ServiceBasedControllerActivator. That's good, and we can use IMvcBuilder.AddControllersAsServices() extension method to use DI to create controllers.
However, IPageModelActivatorProvider currently has only one implementation: DefaultPageModelActivatorProvider. It would be good to be able to instantiate page models using DI. I will implement it myself for now, but I would be happy if you add it in the next version out of the box.
I suppose it should be like that:
````C#
public class ServiceBasedPageModelActivatorProvider : IPageModelActivatorProvider
{
public Func
{
Check.NotNull(descriptor, nameof(descriptor));
return context =>
{
return context.HttpContext.RequestServices.GetRequiredService(descriptor.ModelTypeInfo);
};
}
public Action<PageContext, object> CreateReleaser([NotNull] CompiledPageActionDescriptor descriptor)
{
return null;
}
}
````
Then we can replace the IPageModelActivatorProvider like that:
C#
services.Replace(ServiceDescriptor.Transient<IPageModelActivatorProvider, ServiceBasedPageModelActivatorProvider>());
Note: If you use ServiceBasedPageModelActivatorProvider, then you should somehow register all PageModel classes to DI.
@rynowak thoughts on adding this?
We should do this. I don't think we can should try to build a Pages equivalent to IMvcBuilder.AddControllersAsServices()
@hikalkan would you like to send a PR for this?
Sure, I can. I added to my TODO list and will send a PR soon. Thanks.
Hey, I am new to contribution to open source, I want to pick this up as my first contribution.
Most helpful comment
Fixed in https://github.com/aspnet/Mvc/commit/077b1d87a9862b6821a518b4ecb50ced480576a3