Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF DbContext registered with ServiceStack's Funq is disposed when running unit tests

I am working on an ASP.NET MVC web application that uses ServiceStack and EF. In my AppHost I configure Funq to default to Request reuse scope:

container.DefaultReuse = ReuseScope.Request;

Then I register my EF context.

When running unit tests (i.e. when no HTTP request exists) I get the "DbContext disposed" exception. I assume it's because my context is immediately disposed by Funq in the absence of the HTTP request. Right?

I have previous experience with StructureMap that supports a hybrid reuse (i.e. either per-request if HTTP context exists or per-thread), so how would I configure Func to do the same for me?

like image 339
Caspian Canuck Avatar asked Jan 23 '26 02:01

Caspian Canuck


1 Answers

My bad! Turns out this is not Funq's issue but that of the EF database migrations:

Apparently migrations logic cleans up after itself by disposing of the context. My problem was that I used IDbContextFactory to provide the context to migrations, and inside its Create method I was returning the instance of the context resolved by Funq's container. Which is how the instance in the container ended up disposed after migrations was done with it.

like image 137
Caspian Canuck Avatar answered Jan 25 '26 15:01

Caspian Canuck