简体   繁体   English

InstancePerRequest DbContext ASP.NET MVC

[英]InstancePerRequest DbContext ASP.NET MVC

Registering DbContext in ASP.NET MVC Application as InstancePerRequest .在 ASP.NET MVC 应用程序中将 DbContext 注册为InstancePerRequest ( IoC Autofac ) ( IoC Autofac )

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

Using inside BServiceBService内部BService

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

Trying to register IBService as Singleton.尝试将IBService注册为单例。

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.从请求实例的范围中看不到具有匹配“AutofacWebRequest”标签的范围。

Simplest solution is to register IBService as InstancePerRequest , but there is no reason having PerRequest IBService rather than error message mentioned above.最简单的解决方案是将IBService注册为InstancePerRequest ,但没有理由使用 PerRequest IBService而不是上面提到的错误消息。

How can i use PerRequest DbContext inside Singleton service ?如何在 Singleton 服务中使用PerRequest DbContext

First attempt, you can inject IContainer into BService.第一次尝试,您可以将 IContainer 注入 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.每次,当您想要访问单音内的上下文时,它都会将此请求传递给 IoC 容器,该容器能够返回每个请求的上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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