简体   繁体   中英

InstancePerRequest DbContext ASP.NET MVC

Registering DbContext in ASP.NET MVC Application as InstancePerRequest . ( IoC Autofac )

builder.RegisterType<ADbContext>().As<IADbContext>().InstancePerRequest();

Using inside BService

public class BService : IBService
{
    readonly IADbContext _dbContext;
    public BService(IADbContext dbContext)
    {
        _dbContext = dbContext;
    }
}

Trying to register IBService as Singleton.

builder.RegisterType<BService>().As<IBService>().SingleInstance();

Obviously, this gives me an error

No scope with a tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested.

Simplest solution is to register IBService as InstancePerRequest , but there is no reason having PerRequest IBService rather than error message mentioned above.

How can i use PerRequest DbContext inside Singleton service ?

First attempt, you can inject IContainer into BService. But this will look like Service locator pattern, which is not good. Otherwise, you can define factory interface

public interface IFactory<T>
{
    T GetInstance();
}

Then implement it and register

public class SimpleFactory<T> : IFactory<T>
{
    private IContainer _container;

    public SimpleFactory(IContainer container)
    {
        _container = container;     
    }

    public T GetInstance()
    {
        return _container.Resolve<T>();
    }
}

public class DbContextFactory : SimpleFactory<IADbContext>
{   
    public DbContextFactory(IContainer container):base(container)
    {   
    }
}

Finally, use this factory in your singletone

public class BService : IBService
{
    IADbContext _dbContext =>  _dbContextFactory.GetInstance();
    IFactory<IADbContext> _dbContextFactory

    public BService(IFactory<IADbContext> dbContextFactory)
    {
        _dbContextFactory = dbContextFactory;
    }
}

Each time, when you want to acess to context inside singletone, it will pass this request to IoC container, which able to return context per request.

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