Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2018
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.36 KB | None | 0 0
  1. public sealed class Container : IDisposable {
  2.     private readonly Dictionary<Type, Contract> contracts = new Dictionary<Type, Contract>();
  3.     private readonly Subject<Contract> newContract = new Subject<Contract>();
  4.  
  5.     public IDisposable Register<T>(T contract) where T : Contract {
  6.         if (contract == null) throw new ArgumentNullException("contract");
  7.  
  8.         return this.Register(contract, typeof(T));
  9.     }
  10.  
  11.     private IDisposable Register(Contract contract, Type type) {
  12.         if (contract == null) throw new ArgumentNullException("contract");
  13.         if (type == null) throw new ArgumentNullException("type");
  14.  
  15.         var container = new CompositeDisposable();
  16.         this.RegisterLocal(contract, type).AddTo(container);
  17.         contract.SubContracts.ForEach(c => this.Register(c).AddTo(container));
  18.         return container;
  19.     }
  20.  
  21.     private IDisposable RegisterLocal(Contract contract, Type type) {
  22.         if (!this.contracts.ContainsKey(type) && !this.contracts.ContainsValue(contract)) {
  23.             this.contracts.Add(type, contract);
  24.             this.newContract.OnNext(contract);
  25.         }
  26.         return Disposable.Create(() => this.Unregister(contract));
  27.     }
  28.  
  29.     public void Unregister<T>(T contract) where T : Contract {
  30.         if (contract == null) throw new ArgumentNullException("contract");
  31.         if (this.contracts.ContainsKey(typeof(T))) {
  32.             this.contracts.Remove(typeof(T));
  33.         }
  34.     }
  35.  
  36.     public T Resolve<T>() where T : Contract {
  37.         Contract contract;
  38.         if (this.contracts.TryGetValue(typeof(T), out contract)) {
  39.             return (T) contract;
  40.         }
  41.         return null;
  42.     }
  43.  
  44.     public IObservable<T> ResolveAsync<T>() where T : Contract {
  45.         return Observable.Create<T>(o => {
  46.             Contract contract;
  47.             if (this.contracts.TryGetValue(typeof(T), out contract)) {
  48.                 o.OnNext((T)contract);
  49.                 o.OnCompleted();
  50.                 return Disposable.Empty;
  51.             }
  52.             else {
  53.                 return this.newContract
  54.                     .Where(c => c is T)
  55.                     .Subscribe(c => {
  56.                         o.OnNext((T) c);
  57.                         o.OnCompleted();
  58.                     });
  59.             }
  60.         });
  61.        
  62.     }
  63.  
  64.     public void Dispose() {
  65.         this.contracts.Clear();
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement