在WebApi中使用Autofac注入DBContext时的大量SQL活动会话

时间:2016-01-02 11:56:32

标签: entity-framework asp.net-web-api asp.net-web-api2 autofac dbcontext

我正在使用AutofacWeb Api中注入依赖项。

我为EF InstancePerRequest设置了DBContext范围。

Autofac布线配置:

  public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);

        var config = new HttpConfiguration();

        var builder = new ContainerBuilder();

        builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).InstancePerRequest();

        var asmb = typeof (TrafficDataService).Assembly;
        builder.RegisterAssemblyTypes(asmb).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerRequest();


        builder.RegisterType<TrafficServiceGlobalContext>().As<IUnitOfWork>().InstancePerRequest();
        builder.RegisterType<EMSEntities>().As<IEmsDataModel>().InstancePerRequest();
        builder.RegisterType<ViolationTrafficEntities>().As<IViolationDataModel>().InstancePerRequest();
        builder.RegisterType<TrafficController>().As<IHttpController>().InstancePerRequest();
        builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
        builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest();


        var container = builder.Build();

        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        app.UseAutofacMiddleware(container);

        app.UseAutofacWebApi(config);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(config);
        WebApiConfig.Register(config);
    }

服务获得大量请求,并且在检查我的数据库的活动会话时,我看到数据库上有500个活动会话。

这真的是个问题吗? 如何实现连接池? 有什么想法吗?

更新 所有相关类都依赖于接口。 正如Yacoub Massad在评论区域中所说,这里有一些相关的类签名和构造函数:

    public partial class ViolationTrafficEntities : DbContext, IViolationDataModel
    {
        .
        .
        .
    }        
public class TrafficDataService : ITrafficDataService
    {
        private readonly IViolationDataModel _violationDataModel;
        public TrafficDataService(IViolationDataModel violationDataModel)
        {
            _violationDataModel = violationDataModel;
        }
    }

0 个答案:

没有答案