I have self-hosted WebAPI inside my ASP.NET MVC application. I want to perform some asynchronous action when one of my API action is executed. The asynchronous action has dependency on DbContext along with some other dependencies.
Following is my Simple Injector configuration.
public class SimpleInjectorIntegrator
{
private static Container container;
public static Container Setup()
{
container = new Container();
container.Options.DefaultScopedLifestyle = Lifestyle.CreateHybrid(
defaultLifestyle: new WebRequestLifestyle(),
fallbackLifestyle: new AsyncScopedLifestyle());
container.Register<IBaseRepository<User>, BaseRepository<User>>(Lifestyle.Scoped);
container.Register<ComputationService>(Lifestyle.Scoped);
container.Register<ILog, Logger>(Lifestyle.Scoped);
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
}
public static T Get<T>() where T : class
{
if (container == null)
throw new InvalidOperationException("Container hasn't been initialized.");
return container.GetInstance<T>();
}
}
The Global.asax.cs looks like this.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
var container = SimpleInjectorIntegrator.Setup();
GlobalConfiguration.Configure(WebApiConfig.Register);
...some other code...
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}
}
Below is the API Controller.
public class ExperimentUploadController : ApiController
{
private ComputationService _service = SimpleInjectorIntegrator.Get<ComputationService>();
public IHttpActionResult Started(InputModel model)
{
...Do Something...
var task = Task.Run(() =>
{
_service.Do(model.Id);
});
}
}
The API depends on ComputationService
which performs connects with database using a repository. When I am trying to access the database from ComputationService
, it throws that DbContext is disposed.
ComputationService
code looks like below:
public class ComputationService
{
private IBaseRepository<User> _userRepo = SimpleInjectorIntegrator.Get<User>();
public void Do(int id)
{
///throws here
var user = _userRepo.Get(id);
}
}
I am not sure why this is happening.