Beispiel #1
0
    public static void Main()
    {
        ISingleton IObj1 = null, IObj2 = null;
        int        data = 0;
        //IObj1=Singleton.calling();
        Thread t1 = new Thread(() => { IObj1 = Singleton.calling(); });

        t1.Start();
        Thread.Sleep(2000);
        if (IObj1 != null)
        {
            data = IObj1.getData();
            Console.WriteLine(data);

            IObj1.setData(8);
            data = IObj1.getData();
            Console.WriteLine(data);
        }

        Thread t2 = new Thread(() => { IObj2 = Singleton.calling(); });

        t2.Start();
        Thread.Sleep(2000);

        if (IObj2 != null)
        {
            data = IObj2.getData();
            Console.WriteLine(data);

            IObj2.setData(9);
            data = IObj2.getData();
            Console.WriteLine(data);
        }
    }
Beispiel #2
0
 public static void RemoveInstance(ISingleton instance)
 {
     if (instance != null)
     {
         instances.Remove(instance);
     }
 }
Beispiel #3
0
        private static ISingleton CreateInstance(Type type)
        {
            ISingleton singleton = null;

            if (type.IsSameOrSubClass(typeof(Singleton)))
            {
                singleton = Activator.CreateInstance(type) as Singleton;
            }
            else if (type.IsSameOrSubClass(typeof(SingletonMono)))
            {
                var component = UnityEngine.Object.FindObjectOfType(type);

                if (UnityEngine.Object.FindObjectsOfType(type).Length > 1)
                {
                    throw new Exception($"Singleton: There should never be more than one SingletonMono instacne, type= {type.Name}.");
                }

                if (component == null)
                {
                    GameObject go = new GameObject();
                    go.name = "[Singelton] " + type.Name;
                    go.transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity);

                    component = go.AddComponent(type);
                }

                singleton = component as SingletonMono;
            }

            return(singleton);
        }
Beispiel #4
0
    void LoadSingletonClasses()
    {
        LoadedData.singletonList = new Dictionary <Type, ISingleton>();

        Type[] types = new Type[0];
        Type   t     = typeof(ISingleton);

        types = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(s => s.GetTypes())
                .Where(p => t.IsAssignableFrom(p)).ToArray();


        for (int i = 0; i < types.Length; i++)
        {
            ConstructorInfo info = types[i].GetConstructor(new Type[0]);
            ISingleton      inst = null;

            if (info != null)
            {
                inst = info.Invoke(new object[0]) as ISingleton;

                MonoBehaviour singleton = new GameObject(inst.GetType().FullName).AddComponent(inst.GetType()) as MonoBehaviour;
                DontDestroyOnLoad(singleton.gameObject);

                ISingleton castedSingleton = singleton as ISingleton;
                castedSingleton.RunOnCreated();

                LoadedData.singletonList.Add(types[i], castedSingleton);
            }
        }
    }
Beispiel #5
0
        public override void OnInspectorGUI()
        {
            ++EditorGUI.indentLevel;
            SingletonRoot script = (SingletonRoot)target;

            mConstantRepaint = false;
            for (int i = 0; i < script.singletonInstances.Count; ++i)
            {
                ISingleton inst = script.singletonInstances[i];
                if (inst is MonoBehaviour)
                {
                    continue;
                }

                Type   type    = inst.GetType();
                string name    = inst.GetType().FullName;
                bool   foldout = EditorGUILayout.Foldout(Foldout(name), name);
                if (foldout)
                {
                    SingletonRoot.IEditorDrawer drawer;
                    if (SingletonRoot.editorDrawers.TryGetValue(type, out drawer))
                    {
                        mConstantRepaint |= drawer.constantRepaint;
                        drawer.Draw(inst);
                    }
                }
                Foldout(name, foldout);
            }
            --EditorGUI.indentLevel;
        }
Beispiel #6
0
 public MainWindow(ICalculateService calculateService,
                   ISingleton singleton)
 {
     _calculateService = calculateService;
     this.singleton    = singleton;
     InitializeComponent();
 }
Beispiel #7
0
            /// <summary>
            ///
            /// </summary>
            /// <param name="target"></param>
            /// <returns>Returns true if the validation was a success.</returns>
            public bool OnAwake(ISingleton target)
            {
                if (object.ReferenceEquals(target, null))
                {
                    throw new System.ArgumentNullException("target");
                }
                _target = target;

                //first test if we have the appropriate configuration
                if (_target.component.GetComponentsAlt <ISingleton>().Count() > 1 && !_target.component.HasComponent <SingletonManager>())
                {
                    Debug.LogWarning("Gameobject with multiple Singletons exists without a SingletonManager attached, adding a SingletonManager with default destroy settings.", target.component);
                    _target.component.AddComponent <SingletonManager>();
                }

                //now set up singleton reference
                if (_target.component.IsActiveAndEnabled())
                {
                    this.EnforceThisAsSingleton();
                    _target.ComponentDestroyed   += this.OnComponentDestroyed;
                    GameLoopEntry.LevelWasLoaded += this.OnLevelWasLoaded;
                    return(true);
                }
                else
                {
                    //remove self if it were added
                    this.RemoveThisAsSingleton();
                    return(false);
                }
            }
Beispiel #8
0
 /// <summary>
 /// 销毁单例
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="singleton"></param>
 public static void Dispose(this ISingleton singleton)
 {
     if (singleton != null)
     {
         singleton.OnDispose();
     }
 }
Beispiel #9
0
 public ScopesController(IServiceOne testingServiceOne, IServiceTwo testingServiceTwo, ISingleton singleton, IScoped scoped, ITransient transient)
 {
     this.testingServiceOne = testingServiceOne;
     this.testingServiceTwo = testingServiceTwo;
     this.singleton         = singleton;
     this.scoped            = scoped;
     this.transient         = transient;
 }
Beispiel #10
0
 public SomeController(ITransient transient, IScoped scoped, ISingleton singleton,
                       Func <ITransient> transientFactory)
 {
     Transient        = transient;
     Scoped           = scoped;
     Singleton        = singleton;
     TransientFactory = transientFactory;
 }
 public HomeController(ITransient transientService1, ITransient transientService2, ISingleton singletonService1, ISingleton singletonService2, IScoped scopedService1, IScoped scopedService2)
 {
     this.transientService1 = transientService1;
     this.transientService2 = transientService2;
     this.singletonService1 = singletonService1;
     this.singletonService2 = singletonService2;
     this.scopedService1    = scopedService1;
     this.scopedService2    = scopedService2;
 }
        public ClassConsumer(ISingleton dependency)
        {
            if (dependency == null)
            {
                throw new ArgumentException("dependency not founded");
            }

            this._dependency = dependency;
        }
Beispiel #13
0
 public TestController(ITransient injectedTransientItem, ISingleton injectedSingletonItem, IScoped injectedScopedItem, ILogger <TestController> injectedLogger)
 {
     _theTransient = injectedTransientItem;
     _theSingleton = injectedSingletonItem;
     _theScoped    = injectedScopedItem;
     _theLogger    = injectedLogger;
     _theLogger.LogDebug($"The TestController that was created");
     _theLogger.LogDebug($"The Transient that was injected has data: {injectedTransientItem.Data}");
 }
Beispiel #14
0
 public GenerateController(
     ITransient transient,
     IScoped scoped,
     ISingleton singleton)
 {
     _transient = transient;
     _scoped    = scoped;
     _singleton = singleton;
 }
Beispiel #15
0
 public SampleService(IFoo foo, IBar bar, ISingleton singleton, ITransient transient, IAsyncClass asyncClass)
 {
     _id         = Guid.NewGuid();
     _foo        = foo ?? throw new ArgumentNullException(nameof(foo));
     _bar        = bar ?? throw new ArgumentNullException(nameof(bar));
     _singleton  = singleton ?? throw new ArgumentNullException(nameof(singleton));
     _transient  = transient ?? throw new ArgumentNullException(nameof(transient));
     _asyncClass = asyncClass ?? throw new ArgumentNullException(nameof(asyncClass));
 }
Beispiel #16
0
    public void LifecycleWarningTest()
    {
        IWindsorContainer container = new WindsorContainer();

        container.Register(
            Component.For <ISingleton>().ImplementedBy <Singleton>().LifestyleSingleton(),
            Component.For <ITransient>().ImplementedBy <Transient>().LifestyleTransient()
            );
        ISingleton singleton = container.Resolve <ISingleton>();
    }
Beispiel #17
0
 public AdminUserController(ApplicationDbContext db, IWebHostEnvironment hostEnvironment)
 {
     _db = db;
     _hostEnvironment = hostEnvironment;
     UserVM           = new ApplicationUserViewModel()
     {
         ApplicationUser = new ApplicationUser()
     };
     _iSingleTon = Singleton.GetInstance;
 }
Beispiel #18
0
 public static void Remove(ISingleton singleton)
 {
     if (root.singletonInstances.Remove(singleton))
     {
         if (singleton is MonoBehaviour)
         {
             GameObject.Destroy(((MonoBehaviour)singleton).gameObject);
         }
         SingletonLog.InfoFormat("{0} Removed", singleton.GetType().FullName);
     }
 }
 public CountriesController(ApplicationDbContext context)
 {
     _context        = context;
     this.UnitOfWork = new UnitOfWork(_context);
     CountriesVM     = new CountryViewModel()
     {
         Country = new Country(),
         Total   = 0
     };
     _iSingleton = Singleton.GetInstance;
 }
        public ProductController(ITransient transient1, ITransient transient2, ISingleton singleton1, ISingleton singleton2, IScoped scoped1, IScoped scoped2)
        {
            _transient1 = transient1;
            _transient2 = transient2;

            _singleton1 = singleton1;
            _singleton2 = singleton2;

            _scoped1 = scoped1;
            _scoped2 = scoped2;
        }
Beispiel #21
0
 public static void AddInstance(ISingleton instance)
 {
     if (instance == null)
     {
         return;
     }
     if (instances.Contains(instance) == false)
     {
         instances.Add(instance);
     }
 }
Beispiel #22
0
 public AuthorsController(ApplicationDbContext context, IWebHostEnvironment hostEnvironment)
 {
     _context         = context;
     _hostEnvironment = hostEnvironment;
     AuthorsVM        = new AuthorViewModel()
     {
         Author     = new Author(),
         Authors    = new List <Author>(),
         PagingInfo = new PagingInfo()
     };
     _iSingleTon = Singleton.GetInstance;
 }
 public BooksController(ApplicationDbContext context, IWebHostEnvironment hostEnvironment)
 {
     _context         = context;
     _hostEnvironment = hostEnvironment;
     BooksVM          = new BooksViewModel()
     {
         Books            = new List <Book>(),
         Book             = new Book(),
         GenresViewModels = new List <GenresViewModel>()
     };
     _iSingleton = Singleton.GetInstance;
 }
Beispiel #24
0
    private readonly Dictionary <string, ISingleton> SingletonPool = new Dictionary <string, ISingleton>(); //单例池字典
    /// <summary> 添加单例 </summary>
    public void Add(ISingleton obj)
    {
        string name = obj.ToString();

        if (!SingletonPool.ContainsKey(name))
        {
            SingletonPool.Add(name, obj);
        }
        else
        {
            Debug.Log($"已具有相同名称的实例:{name}");
        }
    }
Beispiel #25
0
        public Combined(ISingleton first, ITransient second)
        {
            if (first == null)
            {
                throw new ArgumentNullException("first");
            }

            if (second == null)
            {
                throw new ArgumentNullException("second");
            }

            Instances++;
        }
Beispiel #26
0
    /// <summary> 删除指定单例 </summary>
    public void Delete(ISingleton obj)
    {
        string name = obj.ToString();

        if (SingletonPool.ContainsKey(name))
        {
            SingletonPool[name].Clear();
            SingletonPool.Remove(name);
        }
        else
        {
            Debug.Log($"实例不存在:{name}");
        }
    }
Beispiel #27
0
 /// <summary>
 /// Get/Create new Singleton for normal class
 /// </summary>
 /// <typeparam name="T">Type of class that contain PRIVATE CONSTRUCTOR</typeparam>
 /// <returns></returns>
 private static T NormalInstance <T>() where T : ISingleton
 {
     System.Type       type         = typeof(T);
     ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance);
     if (constructors.Length == 0)
     {
         throw new System.Exception("Private constructor not found");
     }
     else
     {
         ISingleton value = (ISingleton)constructors[0].Invoke(new object[] { });
         return((T)value);
     }
 }
Beispiel #28
0
        /// <summary>
        /// Main entry funciton
        /// </summary>
        /// <param name="args">command line args</param>
        static void Main(string[] args)
        {
            // initial resolutions
            ISingleton s = Program.GetContainer().Resolve <ISingleton>();
            IMathFunc  m = Program.GetContainer().Resolve <IMathFunc>();

            s.SetVal(m.MathFunc(1.1, 2.2).ToString());
            s = null;

            // test singleton
            s = Program.GetContainer().Resolve <ISingleton>();
            Console.WriteLine(string.Format("Singleton value: {0} (should be 3.3)", s.GetVal()));
            Console.ReadLine();
        }
Beispiel #29
0
        public Combined(ISingleton first, ITransient second)
        {
            if (first == null)
            {
                throw new ArgumentNullException("first");
            }

            if (second == null)
            {
                throw new ArgumentNullException("second");
            }

            Instances++;
        }
Beispiel #30
0
        public void MirandaGetSingletonTest()
        {
            ISingleton singleton = context.Get <ISingleton>();

            Assert.AreEqual(SINGLETON_STRING, singleton.GetString());
            string anotherString = "Change to this string.";

            singleton.ChangeString(anotherString);

            ISingleton anotherInstance = context.Get <ISingleton>();

            Assert.AreNotEqual(SINGLETON_STRING, anotherInstance.GetString());
            Assert.AreEqual(anotherString, anotherInstance.GetString());
        }
Beispiel #31
0
 static Repository()
 {
     foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
     {
         foreach (Type type in assembly.GetExportedTypes())
         {
             if (type.GetInterface(typeof(ISingleton).FullName) != null)
             {
                 ISingleton singleton = (ISingleton)Activator.CreateInstance(type);
                 _singletons.Add(singleton.Name, singleton);
             }
         }
     }
 }
Beispiel #32
0
        public Glorp(IContainerManager containerManager, INormal normal1, INormal normal2, ISingleton singleton1, ISingleton singleton2)
        {
            IKeyed keyed1_1 = containerManager.GetInstance<IKeyed>("keyed-1");
            IKeyed keyed1_2 = containerManager.GetInstance<IKeyed>("keyed-1");
            IKeyed keyed2_1 = containerManager.GetInstance<IKeyed>("keyed-2");
            IKeyed keyed2_2 = containerManager.GetInstance<IKeyed>("keyed-2");

            string format = "{0} Name={1}, Key={2}";
            Console.WriteLine(format, "normal1", normal1.Name, normal1.Key);
            Console.WriteLine(format, "normal2", normal2.Name, normal2.Key);
            Console.WriteLine(format, "singleton1", singleton1.Name, singleton1.Key);
            Console.WriteLine(format, "singleton2", singleton2.Name, singleton2.Key);
            Console.WriteLine(format, "keyed1_1", keyed1_1.Name, keyed1_1.Key);
            Console.WriteLine(format, "keyed1_2", keyed1_2.Name, keyed1_2.Key);
            Console.WriteLine(format, "keyed2_1", keyed2_1.Name, keyed2_1.Key);
            Console.WriteLine(format, "keyed2_2", keyed2_2.Name, keyed2_2.Key);
        }
        public ScopedCombined(ITransient transient, ISingleton singleton)
        {
            if (transient == null)
            {
                throw new ArgumentNullException("transient");
            }

            if (singleton == null)
            {
                throw new ArgumentNullException("singleton");
            }

            if (!(transient is ScopedTransient))
            {
                throw new ArgumentException("transient should be of type ScopedTransient");
            }

            Instances++;
        }
Beispiel #34
0
 public SampleModuleWithSingletonDependency(ISingleton singleton)
 {
     Singleton = singleton;
 }
 public Thing(ITransient transient, ISingleton singleton)
 {
     _transient = transient;
     _singleton = singleton;
 }