brussell
brussell

Reputation: 69

Repository classes aren't getting disposed in ServiceStack

I'm using MVC + EF + ServiceStack. I recently discovered some issues with EF context and stale data. I have repository classes that I'm injecting in the controllers with RequestScope.None. The repository classes aren't getting disposed by the IoC after it is used.

ServiceStack's IoC docs states that if it implements IDisposeable the container should call the dispose method after it is used. I'm wondering if this behavior is different since I'm not calling the objects from within a service stack service?

Registering the repo here:

 container.RegisterAutoWiredAs<LicenseRepository, ILicenseRepository>().ReusedWithin(ReuseScope.None);

Controller:

[Authorize]
public class LicenseController : BaseController
{
    public ILicenseRepository licenseRepo { get; set; }  //injected by IOC
    private ILog Logger;

    public LicenseController()
    {
        Logger = LogManager.GetLogger(GetType());
    }

    public ActionResult Edit(Guid id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        var license = licenseRepo.GetLicense(id);
        if (license == null)
        {
            return HttpNotFound();
        }

        return View(license);
    }
    ...
}

Typical repository class: (dbcontext is getting instantiated in base class)

    public class LicenseRepository: RepositoryBase<LicensingDBContext>, ILicenseRepository,IDisposable
{

    public License GetLicense(Guid id)
    {
        return DataContext.Licenses.Find(id);
    }

      ....

    public void Dispose()
    {
        base.Dispose();
    }
}

Upvotes: 2

Views: 295

Answers (2)

mythz
mythz

Reputation: 143319

ServiceStack only calls Dispose() on dependencies resolved within ServiceStack Requests, i.e. it tracks any disposables resolved from Funq and disposes of them at the end of a ServiceStack request.

Outside the context of a ServiceStack request, ServiceStack doesn't have ownership of it, i.e. it can't know when it's used or no longer needed. Therefore any dependencies resolved needs to be explicitly disposed.

Upvotes: 2

Kritner
Kritner

Reputation: 13765

You aren't using your repo within a using block or explicitly calling dispose on the repo, I would think to get immediate disposal you would need to do one or the other, if it's anything like other implementations of IDisposable.

I'm not familiar with ServiceStack, but like any other IDisposable object you can dispose of it as such (when having it within a using block isn't an option):

public ActionResult Edit(Guid id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    var license = licenseRepo.GetLicense(id);
    licenseRepo.Dispose();
    if (license == null)
    {
        return HttpNotFound();
    }

    return View(license);
}

Upvotes: 1

Related Questions