IOC DI Multi-threaded lifecycle definition in background tasks

I have an application that uses IOC and DI to create and deploy services.

I have a service level that processes some business logic, at the service level I have a repository that interacts with the database. This repository uses a DataContext that is not thread safe.

I want to run some functions in the service asynchronously using background tasks, but I know that this will cause problems with the repository. Thus, I want the repository to be created for each background thread created. How is this achieved? I use StructureMap as an 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();
           });
       }
    }
}
+4
1

DI (, (IIIRC) StructureMap) Per Thread, , , , IService Controller , .

Controller , , IService , .

/ IService Controller. - :

public ThreadSafeService : IService
{
    private readonly IServiceFactory factory;

    public ThreadSafeService(IServiceFactory factory)
    {
        this.factory = factory;
    }

    public void DoSomething()
    {
        this.factory.Create().DoSomething();
    }
}

IServiceFactory :

public interface IServiceFactory
{
    IService Create();
}

IServiceFactory , IService Create, - , .

- .

+6

Source: https://habr.com/ru/post/1534968/


All Articles