Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public sealed class Container : IDisposable {
- private readonly Dictionary<Type, Contract> contracts = new Dictionary<Type, Contract>();
- private readonly Subject<Contract> newContract = new Subject<Contract>();
- public IDisposable Register<T>(T contract) where T : Contract {
- if (contract == null) throw new ArgumentNullException("contract");
- return this.Register(contract, typeof(T));
- }
- private IDisposable Register(Contract contract, Type type) {
- if (contract == null) throw new ArgumentNullException("contract");
- if (type == null) throw new ArgumentNullException("type");
- var container = new CompositeDisposable();
- this.RegisterLocal(contract, type).AddTo(container);
- contract.SubContracts.ForEach(c => this.Register(c).AddTo(container));
- return container;
- }
- private IDisposable RegisterLocal(Contract contract, Type type) {
- if (!this.contracts.ContainsKey(type) && !this.contracts.ContainsValue(contract)) {
- this.contracts.Add(type, contract);
- this.newContract.OnNext(contract);
- }
- return Disposable.Create(() => this.Unregister(contract));
- }
- public void Unregister<T>(T contract) where T : Contract {
- if (contract == null) throw new ArgumentNullException("contract");
- if (this.contracts.ContainsKey(typeof(T))) {
- this.contracts.Remove(typeof(T));
- }
- }
- public T Resolve<T>() where T : Contract {
- Contract contract;
- if (this.contracts.TryGetValue(typeof(T), out contract)) {
- return (T) contract;
- }
- return null;
- }
- public IObservable<T> ResolveAsync<T>() where T : Contract {
- return Observable.Create<T>(o => {
- Contract contract;
- if (this.contracts.TryGetValue(typeof(T), out contract)) {
- o.OnNext((T)contract);
- o.OnCompleted();
- return Disposable.Empty;
- }
- else {
- return this.newContract
- .Where(c => c is T)
- .Subscribe(c => {
- o.OnNext((T) c);
- o.OnCompleted();
- });
- }
- });
- }
- public void Dispose() {
- this.contracts.Clear();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement