HOW CAN I EXTEND AN API CONTROLLER TO HOLD A VARIABLE FOR MY DATABASE CONTEXT?

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
 1589  View(s)
Ratings:
Rate this:

I have many classes like this one. They all have two things in common. They declare a private variable called Context and they have a method to dipose of that.

Is there a way I can create an intermediate class that I could inherit from that has the code to declare the variable and the dispose method? I assume it's easy to do but I am not sure how to declare the variables and the method. Should they be private?

public class TypeController : ApiController
{
    private Context db = new Context();
 
    [Route("GetMapData")]
    public async Task<IHttpActionResult> GetMapData()
    {
        var result = await db.Types
                             .Select(e => new
                             {
                                 Id = e.TypeId,
                                 Name = e.Name
                             })
                             .ToListAsync();
        return Ok(result);
    }
 
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
 
}

 

  1. Tanuj Kumar

    Post:134

    Points:940
    Re: How can I extend an API controller to hold a variable for my database Context?

    You can make a base class that does that, and you'd declare the db variable as protected

    public class BaseController : ApiController
    {
        protected Context db = new Context();
     
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
     
            base.Dispose(disposing);
        }
    }
     
    public class TypeController : BaseController
    {  
        [Route("GetMapData")]
        public async Task<IHttpActionResult> GetMapData()
        {
            var result = await db.Types
                                 .Select(e => new
                                 {
                                     Id = e.TypeId,
                                     Name = e.Name
                                 })
                                 .ToListAsync();
            return Ok(result);
        } 
    }

      Modified On Apr-09-2018 12:00:24 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!