C#MVC在ApplicationDbContext构造函数参数中处理null

编程入门 行业动态 更新时间:2024-10-24 06:26:01
本文介绍了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

本文发布于:2023-11-16 20:47:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1607405.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   参数   MVC   ApplicationDbContext   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!