0

I have a Controller with syntax like this:

public class CrudController<TEntity> : Controller

Now if I need a CrudController for Entity User, I just need to extend the CrudController like this

UserCrudController : CrudController<User>

Its working just fine. But, the thing is, the UserCrudController is simply empty. Also, there are some other CrudControllers which are empty too.

Now, I am looking for a way to avoid writing the empty crud controllers. I simply want to create Instances of CrudController with appropriate generic argument. Perhaps by a strict naming convention as described bellow.

  • The URL will be like: @Html.ActionLink("Create", "UserCrud")
  • When the URL will be received, it will try to locate the controller named UserCrud (The default thing)
  • If it fails to locate UserCrud, Crud<User> will be created.

Now, I can do the things I want to do. But exactly where do I do these? Where is the url parsed in mvc?

Mohayemin
  • 3,841
  • 4
  • 25
  • 54

1 Answers1

1

With help of Craig Stuntz's comment on the question and this question and its accepted answer, I have solved my problem.

I have implemented a custom CotrollerFactory

public class CrudControllerFactory : DefaultControllerFactory {
    protected override Type GetControllerType(System.Web.Routing.RequestContext requestContext, string controllerName) {
        Type controllerType = base.GetControllerType(requestContext, controllerName);

        if(controllerType == null) {
            int indexOfEntityEnd = controllerName.LastIndexOf("Crud");
            if(indexOfEntityEnd >= 0) {
                string entityName = controllerName.Substring(0, controllerName.Length - indexOfEntityEnd - 1);
                // Get type of the CrudController and set to controller tye
            }
        }

        return controllerType;
    }
}

And then in Application_Start(), I added this line:

ControllerBuilder.Current.SetControllerFactory(typeof(CrudControllerFactory));

Community
  • 1
  • 1
Mohayemin
  • 3,841
  • 4
  • 25
  • 54