[英]How can I use the same instance of a non-static class in every controller in an ASP.NET page?
I am new to the ASP.Net framework, and I am currently struggling to understand how to manage lifetimes of objects. 我是ASP.Net框架的新手,目前正在努力了解如何管理对象的生存期。
In a more specific case I am currently facing a problem in my application: 在更具体的情况下,我目前在应用程序中遇到问题:
I want to have a class starting with my application, which should run in the background and do some work which results in some data my application controllers are working with later on. 我想有一个从我的应用程序开始的类,该类应在后台运行并做一些工作,这些工作将在以后的应用程序控制器中处理一些数据。
I would therefore try to create this class' object in my Global.asax.cs
, so it can start and run as soon as my application is running as well. 因此,我将尝试在Global.asax.cs
创建此类的对象,以便它可以在我的应用程序也运行时立即启动并运行。
However, how can I pass this instance to controllers which might get called later on then? 但是,如何将这个实例传递给控制器,该控制器随后可能会被调用?
Currently, my only idea would be to make my data-collection class static
, which I am not really happy with, as I would like to avoid static classes as much as possible. 当前,我唯一的想法是使我的数据收集类成为static
类,对此我并不满意,因为我想尽可能避免使用静态类。
Is there any solution to this? 有什么解决办法吗?
You could create a class with static members or alternatively a singleton to hold data and logic in one place. 您可以创建一个具有静态成员的类,或者创建一个单例以将数据和逻辑保存在一个地方。 The processing inside the class could be started by a call to one of its methods in Global.asax.cs
in Application_Start
. 可以通过在Application_Start
调用Global.asax.cs
中的方法之一来启动类内部的处理。
Since more than one thread may access static data collection simultaneously, the data collection may require multi-thread access handling. 由于一个以上的线程可以同时访问静态数据收集,因此数据收集可能需要多线程访问处理。
Options from top of my head: 我脑海中的选择:
Application Variable System.Web.HttpContext.Current.Application["Name"] = "Value";
应用程序变量 System.Web.HttpContext.Current.Application["Name"] = "Value";
You can add your whole object in the application variable and will be able to access the same object everywhere in your application life time. 您可以将整个对象添加到应用程序变量中,并且将能够在应用程序生存期内的任何地方访问同一对象。
Singleton which still a static way: https://msdn.microsoft.com/en-us/library/ff650316.aspx 单例仍然是静态方式: https : //msdn.microsoft.com/zh-cn/library/ff650316.aspx
Using a static variable 使用静态变量
If you are using a dependency injection framework such as Autofac, you could instantiate a new instance of your class and register it as a single instance (singleton) with the DI framework. 如果使用的是诸如Autofac之类的依赖项注入框架,则可以实例化类的新实例,并使用DI框架将其注册为单个实例(单例)。
// In your DI config -- Autofac used here as an example
Foo myFoo = new Foo();
myFoo.Start();
builder.RegisterInstance<Foo>(myFoo).AsSelf().SingleInstance();
Then, just add it as an argument to the constructor of your controllers. 然后,只需将其作为参数添加到控制器的构造函数即可。
public class HomeController : Controller
{
private readonly Foo _myFoo;
public HomeController(Foo myFoo)
{
_myFoo = myFoo;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.