Is it possible to use Thread Scoped Lifestyle in method with Simple Injector

Viewed 1109

I have the following code:

public class TempForm : Form
{
    private readonly IGoogleAuth _googleAuth;
    private readonly IComAssistant _comAssistant;

    public TempForm(IGoogleAuth googleAuth, IComAssistant comAssistant)
    {
        _googleAuth = googleAuth;
        _comAssistant = comAssistant;

        InitializeComponent();
    }

    private void ButtonClick(object sender, EventArgs e)
    {
        var excelThread = new Thread(() =>
        {
            //NEED NEW INSTANCE OF EXCEL_APP PER THREAD
            using (IExcelApp excel = new ExcelApp(_comAssistant))
            {
                //Do stuff with excel.
                excel.CreateWorkBook();
                //...
            }
        });

        excelThread.SetApartmentState(ApartmentState.STA);
        excelThread.Start();
    }

    private void InitializeComponent()
    {
        //Initialize form components
    }
}

I have no problems with IGoogleAuth or IComAssistant services, because they are registered as Singletone in container an I injected them in form constructor.

But in ButtonClick method I need the new instance of ExcelApp per each new thread.

I can do it is such way:

using (ThreadScopedLifestyle.BeginScope(container)) {
    var excel = container.GetInstance<IExcelApp>();
}

But in this way I need to pass container which declared in Program.cs into my TempForm form.

Is it possible to achive such behavior without passing container itself?

If no - what is the best practices to use container instance in several places. We need to make it as singleton, or put them in own ServiceLocator implementation?

Thanks.

1 Answers
Related