Static classes that require the Initialization method to be called previously used - is everything all right?

In my project, I have several static “service” classes that should be easily accessible throughout the project, and therefore they are static. However, in order to initialize them, I have to pass them data that is only available at startup time, which leads to the fact that the code is similar to this:

public static class VisualStudioEvents
{
    private static Data _data;

    public static void Initialize(Data data)
    {
        _data = data;
    }

    public static void Func()
    {
        AssertInitialized(_data);

        // Code of actual Func() goes here.
    }
}

What do you think about this? Is there any other project that should be applied here? Or is this design acceptable?

Thank!

+3
source share
5 answers

I would be very comfortable. The only change I would make is to enforce it as soon as:

    public static void Initialize(Data data)
    {
        if (data == null) throw new ArgumentNullException("data");
        if (Interlocked.CompareExchange(ref _data, data, null) != null)
        {
            throw new InvalidOperationException("Already initialized");
        }
    }

oh -I guess Data , .

+5

, , , . , .

, - inversion of control, , . IoC singleton , .

, :

public class VisualStudioEvents
{
    public VisualStudioEvents(VisualStudioEventsConfig config)
    {
        // ...
    }

    // ...
}

VisualStudioEventsConfig, IoC , . VisualStudioEvents .

+4

, , Singleton, Data , , Data .

, Data , , / .

+3

VisualStudioEvents , API Visual Studio.

, VisualStudioEvents - , . . - .

edit: , , , . , , , component. static cling .

+2

Instead of a static class, you can try using a singleton pattern . This would also make code verification easier.

0
source

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


All Articles