Structuremap - dependency injection - EF Core DBContext lifetime per request

asp.net-web-api dependency-injection entity-framework-core structuremap

Question

Has anyone had any luck setting up an EF Core DBContext with Structuremap "correctly" (what is correctly?)

DBContext needs to be a singleton across the lifetime of the request.

I understand that the default lifecycle is Transient. I understand that that will get a nested container, which effectively means "per request" when running under web api / mvc? (see this)

But, looking at this code, isn't the dbcontext going to be an Application Lifetime singleton?

public class DistributedTaskRegistry : Registry
{
    public DistributedTaskRegistry()
    {
        For<DistributedTaskDbContext>().Use(() => new DistributedTaskDbContextFactory().CreateDbContext(null));
        For<IDistributedTaskRepository>().Use<DistributedTaskRepository>();
    }
}

NB this is a "legacy" .Net Framework 4.7 Web Api using EF Core

Edit What happened to HttpContextScoped?

1
1
1/10/2018 10:57:09 AM

Popular Answer

Confirmed: the default lifetime is transient, and with StructureMap that means Per Request Lifetime.

If you want an app lifetime Singleton you need to specify it.

For<IDistributedTaskRepository>().Use<DistributedTaskRepository>().Singleton();
0
3/19/2018 4:48:14 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow