I have a application that uses IOC and DI to create and inject services.
I have a service layer that handles some business logic, in the service layer I have a repository that communicates with the database. That repository is using a DataContext which is not thread safe.
I want to run some functions on the service asynchronously using background tasks but know that this will cause issues with the repository. Thus I want the repository to be created for every background thread created. How is this achieved? I'm using StructureMap as the IoC.
public class Service : IService
{
IRepository _repository;
public Service(IRepository repository)
{
this._repository = repository;
}
public void DoSomething()
{
// Do Work
_repository.Save();
}
}
public class Controller
{
IService _service;
public Controller(IService service)
{
this._service = service;
}
public Action DoSomethingManyTimes()
{
for(int i =0; i < numberOfTimes; i++)
{
Task.Factory.StartNew(() =>
{
_service.DoSomething();
});
}
}
}