Q:version info:
Orleans : 2.3.0
EF Core:2.2.3
services.AddDbContextPool<TestContext>(options =>
{
options.UseSqlServer("");
});
public class TestGrain : Grain,ITest
{
private TestContext _testContext;
public TestGrain(TestContext testContext)
{
_testContext = testContext;
}
public void Test()
{
var testContext = ServiceProvider.GetRequiredService<TestContext>();
}
}
I used the above 2 ways to get the context, I got the context used in the last call, not a new context.
A1:
Grains are not recreated for every call, so constructor injection (public TestGrain(TestContext testContext)
) will not work. The second approach (ServiceProvider.GetRequiredService<TestContext>()
inside a grain method) should work: each grain activation has its own dependency injection scope.
AddDbContext
registers contexts using Scoped
lifetime by default. That means that you will have one context per grain activation. You can change this behavior: https://docs.microsoft.com/en-au/dotnet/api/microsoft.extensions.dependencyinjection.entityframeworkservicecollectionextensions.adddbcontext?view=efcore-2.1
I do not see any overload to change the behavior for AddDbContextPool
, however: https://docs.microsoft.com/en-au/dotnet/api/microsoft.extensions.dependencyinjection.entityframeworkservicecollectionextensions.adddbcontextpool?view=efcore-2.1
It may be worth opening an issue or PR in the EF Core repo to implement that
You can implement the behavior you want using a base class like this:
public class GrainBase : Grain, IIncomingGrainCallFilter { public IServiceProvider RequestServices { get; set; } public async Task Invoke(IIncomingGrainCallContext context) { var scope = this.ServiceProvider.CreateScope(); try { this.RequestServices = scope.ServiceProvider; await context.Invoke(); } finally { scope.Dispose(); this.RequestServices = null; } } } public class MyGrain : GrainBase, IMyGrain { public Task<int> MyMethod() { var context = this.RequestService.GetRequiredService<MyDbContext>(); // use db context } }
A2:
Just adding an alternative method...
This registers a bare-bones factory of transient contexts:
.ConfigureServices(services => { services.AddDbContext<RegistryContext>(options => { options.UseInMemoryDatabase("SomeDatabase", _registryContextRoot); }, ServiceLifetime.Transient); services.AddSingleton<Func<RegistryContext>>(_ => () => _.GetService<RegistryContext>()); })
Then the grain requests the factory:
public class StorageRegistryGrain : Grain, IStorageRegistryGrain { private readonly Func<RegistryContext> _factory; public StorageRegistryGrain(Func<RegistryContext> factory) { _factory = factory; }
Then grain methods request a new context as and when required:
public async Task RegisterChannelUserAsync(ChannelUser entity) { using (var context = _factory()) { // do stuff here } }