Tip to Cleaning Up the Controller Code

There are always cleaner and simpler ways of doing things. This topic is a matter of preference. Consider this approach to clean out some lines of codes from your ASP.Net application's controllers.

Note: If you are using TransactionScope, this approach is not recommended.

If you have for example a TestRepository, you will use it in your controller's action codes as follows:

    using (TestRepository tr = new TestRepository())
    {
        ...
    }

This code block can appear in each of your action codes using TestRepository. Three extra lines is not that bad, right? Well, if you have 10 actions in your controller, that's 30 extra lines! What if you just want to make it look a little cleaner?

A way to clean this up is to override the controller's OnActionExecuting() and OnActionExecuted() methods. This way, your action methods' codes can focus on just consuming TestRepository.

    public class TestController : Controller
    {
        private TestRepository TestRepository { get; set; }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            TestRepository = new TestRepository();
            base.OnActionExecuting(context);
        }

        public override void OnActionExecuted(ActionExecutedContext context)
        {
            TestRepository.Dispose();
            base.OnActionExecuted(context);
        }
        ...
    }

Get the full sample code at GitHub Mendz wiki Sample: TestController.

Get Mendz.Data and start writing "cleaner" codes.

Comments