clean-architecture-manga icon indicating copy to clipboard operation
clean-architecture-manga copied to clipboard

What is the impact of chaning EFCore lifecycle to Transient?

Open Blackleones opened this issue 4 years ago • 0 comments

Hi,

I am fascinated by this project and I would like to use it as a model for a project with a Blazor front-end. I am studying the project's architecture. It is interesting but I have a question:

Unfortunately, (actually) EFCore doesn't fit well with Blazor. As you can see here, the first time you have at least two async methods that interact with EFCore, it will crash because it doesn't manage multi request in the same DbContext instance. So, to solve this problem I had to change the lifetime of EFCore from Scoped (default) to Transient. This has a big side effect: every time you ask for an instance that has a DbContext dependency, the DI Container will create a new instance of DbContext and so the change tracker will be empty. Take the following code from DepositUseCase

var customer = await this._customerService.CreateCustomer(input.SSN, this._userService.GetUserName())
                .ConfigureAwait(false);
            var account = await this._accountService.OpenCheckingAccount(customer.Id, input.InitialAmount)
                .ConfigureAwait(false);
            var user = await this._securityService
                .CreateUserCredentials(customer.Id, this._userService.GetExternalUserId())
                .ConfigureAwait(false);

            customer.Register(account.Id);

            await this._unitOfWork.Save()
                .ConfigureAwait(false);

If EFCore lifetime is set to Transient then _customerService, _accountService, and _unitOfWork have 3 different instances of DbContext so 3 different instances of change tracker. So, when we run this._unitOfWork.Save() it will not save anything because its internal change tracker didn't register any changes.

Blackleones avatar Feb 28 '20 12:02 Blackleones