C#MVC在ApplicationDbContext构造函数参数中处理null [英] C# MVC Handling nulls in ApplicationDbContext Constructor parameters

查看:177
本文介绍了C#MVC在ApplicationDbContext构造函数参数中处理null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在ApplicationDbContext构造函数中使用会话值.但是在我的大型应用程序中,我使用了在后台运行的线程.当该Threading方法命中ApplicationDbContext构造方法时,由于请求已完成,因此无法获取会话值.我得到了空引用异常,因此应用程序崩溃了.

I have been using Session Value in the ApplicationDbContext Constructor. But in my big application somewhere i have used Threading which runs in background. And when that Threading method hits the ApplicationDbContext Constructor it doesn't get the Session Value as request is already completed. I get null reference exception, so the Application crashes.

以下为ApplicationDbContext构造函数代码:-

Following is ApplicationDbContext Constructor Code :-

public ApplicationDbContext(string schemaname, string connString = "")
            : base(connString)
        {
            SchemaName = schemaname;
            ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
        }

        public ApplicationDbContext(string schemaname)
            : this(schemaname, System.Web.HttpContext.Current.Session["ConnStringName"].ToString())
        {
        }

如何在上述构造函数中处理空会话?

How to handle null sessions in the above constructor?

推荐答案

那是一个很差的抽象,如果您使用的是mvc,请不要在DbContext的构造函数中放置与http上下文有关的任何内容,尤其是HttpContext.Current/web api.

That is a poor abstraction, do not put anything related to the http context in the constructor of the DbContext especially the HttpContext.Current if you are using mvc/web api.

您应该做的是使用IoC(DI)框架,例如 AutoFac .创建将HttpContextBase注入到构造函数中的执行上下文类型(具有匹配的接口),然后从Session中提取要使用的连接字符串.注册您的DbContext类型,以将您的Execution类型注入其构造函数中,并从中初始化连接字符串.这样可以为您提供出色的SoC(关注点分离),代码不再依赖于正在执行的线程上下文,并且可以简化单元测试.

What you should be doing is using an IoC (DI) framework like AutoFac. Create an execution context type (with matching interface) that has the HttpContextBase injected into the constructor and then extract the connection string you want to use from the Session. Register your DbContext type to have your Execution type injected into its constructor and initialize the connection string from it. That will give you nice SoC (seperation of concerns), code is no longer dependent on the executing thread context, and allow for easier unit testing.

关于如何使用MVC设置IoC的教程很多,还有许多IoC框架可供选择.

There are many tutorials out there on how to setup IoC with MVC and many IoC frameworks to choose from.

这篇关于C#MVC在ApplicationDbContext构造函数参数中处理null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆