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?

2
  • 1
    You don't need to parse the URL. You just need to write a ControllerFactory. Commented Jun 21, 2012 at 3:47
  • Ok, let me learn about ControllerFactory. I'll be back soon. Commented Jun 21, 2012 at 3:48

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.