2025년 6월 15일 일요일

c# 싱글컨테이너

프로그램상 하나만 존재하는데 컨테이너에 넣어서 DI한다던가 할때 쓰는 아이


/// <summary>
/// 싱글톤 하나만 있는 클래스들을 모아놓은 컨테이너
/// </summary>
public class SingleContainer
{
     private SingleContainer() { }
     private static readonly Lazy<SingleContainer> _instance = new Lazy<SingleContainer>(() => new SingleContainer());
     public static SingleContainer Instance => _instance.Value;

     //내부 딕셔너리
     private readonly ConcurrentDictionary<Type, object> _objes = new ConcurrentDictionary<Type, object>();

     //등록
     public void Register<T>(T target_obj) where T : class
     {
         _objes[typeof(T)] = target_obj;
     }

     //Get (가져오기)
     public T GetObj<T>() where T : class
     {
         return _objes.TryGetValue(typeof(T), out var target_obj) ? target_obj as T : null;
     }

     //해당클래스가 들어있는지 여부
     public bool IsContains<T>() where T : class
     {
         return _objes.ContainsKey(typeof(T));
     }

     //해당클래스 삭제
     public void RemoveObj<T>() where T : class
     {
         _objes.TryRemove(typeof(T), out _);
     }
    
}

댓글 없음:

댓글 쓰기