Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing an instantiated class among multiple objects in C#

Tags:

c#

wpf

I currently have a class which I instantiate when I start my program. The class itself will create a new thread and begin to search for broadcasts from routers.

I have other windows, other then MainWindow, which needs to be able to access the data stored within the instance of this class. However, I'm not sure as to how the other windows can reference this data.

Is there some other way I can store the instance of this class so that it is accessible application wide? I need it to start right when the rest of the application starts, so it seemed logical (to me) to have the class be instantiated in the first window.

namespace Lalu_WPF
{
    public partial class MainWindow : Window
    {
        // data storage for program
        public FindRouter finder = new FindRouter();

        public MainWindow()
        {
......
like image 388
BSchlinker Avatar asked Dec 06 '25 16:12

BSchlinker


2 Answers

Don't make Singleton (notice the capital letter). It is error prone in multiple threads environments(muttable Singletons) and bad for testing.

What are your requirements?

Do you have to have one object in one application or one object in whole CLR?

I bet the first one.

Make an object in your App class (App.xaml.cs) and then acces it via getter

App MyApplication = ((App)Application.Current);
MyApplication.Router;
like image 143
Lukasz Madon Avatar answered Dec 08 '25 05:12

Lukasz Madon


Don't use a Singleton, it makes unit testing hard and your code surprising.

Give classes which need access to an instance the instance. That means that every class which needs this single instance should accept either by a constructor argument or setter. Whoever creates the class is then in charge of supplying the dependency. This is called Dependency Injection.

like image 24
Chris Pitman Avatar answered Dec 08 '25 06:12

Chris Pitman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!