Home > DeveloperSection > Forums > How can I extend an API controller to hold a variable for my database Context?
Ankit Singh

Total Post:341

Points:2389
Posted on    January-26-2015 10:38 PM

 ASP.Net C#  ASP.NET MVC 
Ratings:


 1 Reply(s)
 1032  View(s)
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);

    }

 

}

 



Tanuj Kumar

Total Post:134

Points:940
Posted on    January-27-2015 12:12 AM

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

    } 

}


Don't want to miss updates? Please click the below button!

Follow MindStick