How can I make a class global for the whole application?

I would like to access the class throughout the application, how to do this?

To make this clearer, I have a class somewhere where some code is used. I have another class that uses the same code. I do not want to duplicate, so I would like to name the same code in both cases, using something. In php, I would just include ("abc.php") in both ... I don't want to create an object every time I want to use code.

+4
source share
4 answers

The concept of global classes in C # is just a simple question about referencing the corresponding assembly containing the class. After you have a link to the desired assembly, you can refer to the choice of the class either by its completeness of the type name, or by importing the namespace containing the class. ( Specific instance or static access to this class)

or

You may have a Singleton class to use it everywhere, but some people do not recommend you continue this way.

+4
source

Do you want to access a class or access an instance of a class everywhere?

You can make it a static class - public static class MyClass { } - or you can use the Singleton Pattern .

For a singleton template in its simplest form, you can simply add a static property to a class (or some other class) that returns the same instance of the class as this one:

 public class MyClass { private static MyClass myClass; public static MyClass MyClass { get { return myClass ?? (myClass = new MyClass()); } } private MyClass() { //private constructor makes it where this class can only be created by itself } } 
+3
source

The other answers you received about using a static class or singleton pattern are correct.

Please note, however, that this compromises your ability to test. In general, if possible, prefer dependency injection over globally accessible classes. I know that this is not always possible (or practical).

Just on this you should also look at the abstract factory template . This allows you to have a famous factory class that creates the actual instance of the class you are using. For example, to have global access to the logging class, do not directly create a logging class. Instead, use factory log to create one for you and return the interface to the logging class. Thus, it is easier to swap different logging classes.

+1
source

Since you do not want to create an object every time, and it sounds like you are talking about some methods of the utility ...

I suggest you use static methods in the assembly, which you can specify where necessary

+1
source

Source: https://habr.com/ru/post/1277592/


All Articles