Feras Taleb
Feras Taleb

Reputation: 738

IDisposable ASP.net MVC Controller

I'm creating an EntityFramework object in the default constructor of my Controller.

To free the memory after calling action method inside any controller, I want to make the controller disposable. Is this a good idea?

public somethingController : Controller , IDisposable 
{
    // implement the dispose method here 
    public void Dispose ()
    {
        EntityFrameWorkObject.Dispose();
    }
}

what do you think?

Upvotes: 4

Views: 1028

Answers (3)

Stuart Lawrence
Stuart Lawrence

Reputation: 19

Yes, that is right.

public somethingController : Controller 
{
    // implement the dispose method here 
    public void Dispose ()
    {
        EntityFrameWorkObject.Dispose();
    }
}

You don't need to add IDisposable because the controller call already implements it.

Upvotes: 0

archil
archil

Reputation: 39501

Yes, that is good idea. Actually it's recommended pattern and is generally used. If you want to have class wide object, and want to free its resources after class is freed, you do it in Dispose()

Upvotes: 0

Nuri YILMAZ
Nuri YILMAZ

Reputation: 4331

I recommend IHttpModule implementation for dispose datacontext object. My actual code working with Microsoft unity.

public void Init(HttpApplication application)
{
    application.EndRequest += new EventHandler(this.Application_EndRequest);
}

private void Application_EndRequest(object source, EventArgs e)
{
    IoCWorker.Resolve<IRepositoryContext>().Terminate();
}

Upvotes: 2

Related Questions