I have the following projects:
- .Net Standard 2.0 Service Lib
- Asp.Net Web API Project
- WPF Core 3.1 App
The plan was to share the Service layer between the API and the WPF App. In the Web API I add a scoped UnitOfWork Service that itself uses scoped DbContexts
services.AddScoped<IUnitOfWork, UnitOfWork>();
The Service Layer uses the UnitOfWork for committing several queries across services (which are added scoped was well) in one transaction. This works as expected.
Service1:
public Service1(IService2 service2,IUnitOfWork unitOfWork)
{
...
}
public async DoSomething()
{
_unitOfWork.DBContext.SomeTable.Add(new SomeTableRecord())
_service2.AddSomeDbRecord(saveInstant:false); //adds a record in another table without saving
await _unitOfWork.SaveAllChanges(); //saves both db changes (inserts) in one transaction
}
Service 2:
public Service2(IUnitOfWork unitOfWork)
{
...
}
public async AddSomeDbRecord(bool saveInstant)
{
_unitOfWork.DBContext.SomeTable2.Add(new SomeTable2Record())
if(saveInstant)
await _unitOfWork.SaveAllChanges(); //saves both db changes (inserts) in one transaction
}
Now when adding my WPF Project where I don't have the Scope of a "WebRequest" anymore, what is a good way to define the scope. Ideally i would like the scope to be around the full chain of calls to a Services method.
I believe this would do what I wanted it to do:
using (var serviceScope = Host.Services.CreateScope())
{
var services = serviceScope.ServiceProvider;
var service1 = services.GetRequiredService<Service1>();
service1.DoSomething();
}
...but this is obviously not nice or straightforward to write for every call to the service lib and I cannot use ViewModel Constructor Injection for the services.
A scope per ViewModel Instance would be okay too I guess but I don't know how to do this (I'm using MVVM Pattern with a ViewModelLocator)
I would want to stay with Microsoft.Extensions.DependencyInjection as the DI framework as this is also what I'm using in the ASP.Net Project.