Do I still have to implement a singleton class manually in .net even when using .Net4.0?

As soon as a singleton pattern is understood, writing the next singleton classes in C # is a brainless exercise. I hope the framework helps you by providing an interface or base class for this. Here is how I imagine it:

public sealed class Schablone : ISingleton<Schablone>
{
    // Stuff forced by the interface goes here

    // Extra logic goes here
}

Is there what I'm looking for?

Is there any syntactic sugar for building a singleton class - be it with an interface, class attribute, etc.?

Is it possible to write a useful and bulletproof ISingleton? Try to try?

Thank!

+3
source share
8 answers

, .NET . . API , , , .

. ( - , ) . , , , .

[ , . , Google . , .]

+1

, ?

, , , , . , , .

# - . , , .

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();
    public static Singleton Instance { get { return instance; } }

    private Singleton() {}

    // Omit if you don't care about type initializer laziness
    static Singleton() {}
}

, , , , . , , , .

, , , ... , , , - "" ( - ), .

( , ), , , . , . , - , .

+4

? . , , .

, , , . .

+3

( ), .

, , , ( , ):

public static class Singleton<T> where T: class, new() {
    public static T Instance {
        get {
            return Nested.instance;
        }
    }

    private static class Nested {
        public static readonly T instance = new T();

        static Nested() {}
    }
}

, singleton, .

:

Singleton<MyClass>.Instance.DoSomething();
+2

, .

?

, , ( , ).

+1

Inversion of Control .

With StructureMap, you can declare any type as a singleton:

ObjectFactory.Initilialize(x => x.ForSingletonOf<Schablone>());

To get it:

ObjectFactory.GetInstance<Schablone>();
+1
source

.Net 4.0 comes with MEF. And you can use MEF to create singleton code. Through a common creation policy. I will dig a sample code ...

EDIT ----

even better, here is something doco ....

http://mef.codeplex.com/wikipage?title=Parts%20Lifetime&referringTitle=Guide

+1
source

To cut. Paste. Further.

+1
source

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


All Articles