Mvc: Request: ServiceBasedPageModelActivatorProvider

Created on 3 Nov 2017  路  7Comments  路  Source: aspnet/Mvc

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.

3 - Done enhancement up-for-grabs

Most helpful comment

All 7 comments

I suppose it should be like that:

````C#
public class ServiceBasedPageModelActivatorProvider : IPageModelActivatorProvider
{
public Func CreateActivator([NotNull] CompiledPageActionDescriptor descriptor)
{
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.

Was this page helpful?
0 / 5 - 0 ratings