简体   繁体   中英

Can I use an AutFac factory to create my DbContext

I am trying to implement an auto-refresh using MemoryCache by specifying a CacheEntryUpdateCallback delegate that is called when the cached item expires. The delegate calls a method in my repository:

public async Task<List<Foo>> GetFoos()
{
   return await _dbContext.Foos.ToListAsync();
}

That throws an exception in the callback because the context has already been disposed (the original HttpRequest has long since returned)

So I tried using an Autofac factory to inject my dependency instead:

public FooRepository(Func<<IFooContext> dbContextFactory)
{
    _dbContextFactory = dbContextFactory;
}

public async Task<List<Foo>> GetFoos()
{
   return await _dbContextFactory().Foos.ToListAsync();
}

That gave me a different exception:

Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.

What about this "Owned" factory thing?

public FooRepository(Func<Owned<IFooContext>> dbContextFactory)
{
    _dbContextFactory = dbContextFactory;
}

public async Task<List<Foo>> GetFoos()
{
   using(var factory = _dbContextFactory())
   {
       return await factory.Value.Foos.ToListAsync();
   }
}

Nope, same problem:

Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.

What can I do to get around this problem?

you should have hosted service for long run process and kind of refresh queue to feed it

with hosted service you can get DbContext in temporary scope as follow

public class TimedHostedService : IHostedService
{
    private readonly IServiceScopeFactory scopeFactory;

    public TimedHostedService(IServiceScopeFactory scopeFactory)
    {
        this.scopeFactory = scopeFactory;
    }

    private void DoWork()
    {
        using (var scope = scopeFactory.CreateScope())
        {
            var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>();
        }
    }
}

about hosted service

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM