简体   繁体   中英

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.

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.

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.

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 .

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:

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.

// 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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