annotate Implab/ServiceLocator.cs @ 86:b33832ab0262 v2

ServiceLocator: added a cleanup callback to the service registration method
author cin
date Mon, 06 Oct 2014 03:41:17 +0400
parents 48763f3b5db8
children 79badb3ed195
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
1 using System;
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
2 using System.Collections.Generic;
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
3
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
4 namespace Implab {
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
5 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
6 /// Коллекция сервисов, позволяет регистрировать и получать сервисы.
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
7 /// </summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
8 public class ServiceLocator: Component, IServiceLocator, IServiceProvider {
86
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
9 // запись о сервисе
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
10 struct ServiceEntry : IDisposable {
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
11 public object service; // сервис
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
12 public bool shared; // признак того, что сервис НЕ нужно освобождать
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
13 public Func<object> activator; // активатор сервиса при первом обращении
86
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
14 public Action<object> cleanup; // функция для очистки сервиса
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
15 public List<Type> associated; // ссылки на текущую запись
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
16 public Type origin; // ссылка на оригинальную запись о сервисе
86
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
17
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
18 #region IDisposable implementation
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
19
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
20 public void Dispose() {
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
21 if (shared)
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
22 return;
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
23 if (cleanup != null)
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
24 cleanup(service);
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
25 else {
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
26 var d = service as IDisposable;
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
27 if (d != null)
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
28 d.Dispose();
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
29 }
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
30 }
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
31
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
32 #endregion
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
33 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
34
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
35 // словарь существующих сервисов
69
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
36 readonly Dictionary<Type, ServiceEntry> m_services = new Dictionary<Type,ServiceEntry>();
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
37
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
38 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
39 /// Получает объект предоставляющий сервис <typeparamref name="T"/>.
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
40 /// </summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
41 /// <typeparam name="T">Тип запрашиваемого сервиса</typeparam>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
42 /// <returns>Объект, реализующий сервис</returns>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
43 /// <exception cref="KeyNotFoundException">Сервис не зарегистрирован</exception>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
44 public T GetService<T>() {
69
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
45 object result;
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
46 if (TryGetService(typeof(T), out result))
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
47 return (T)result;
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
48 throw new ApplicationException (String.Format ("{0} doesn't provide {1} service", this, typeof(T)));
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
49 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
50
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
51
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
52 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
53 /// Пытается получить указанный сервис, в случае, если компонента не предоставляет требуемый сервис
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
54 /// не возникает исключений.
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
55 /// </summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
56 /// <typeparam name="T">Тип требуемого сервиса.</typeparam>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
57 /// <param name="service">Объект реализующий сервис, или <c>default(T)</c> если такового нет.</param>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
58 /// <returns><c>true</c> - сервис найден, <c>false</c> - сервис не зарегистрирован.</returns>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
59 public bool TryGetService<T>(out T service) {
69
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
60 object result;
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
61 if (TryGetService(typeof(T), out result)) {
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
62 service = (T)result;
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
63 return true;
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
64 }
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
65 service = default(T);
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
66 return false;
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
67 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
68
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
69 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
70 /// Получает объект предоставляющий сервис <paramref name="serviceType"/>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
71 /// </summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
72 /// <param name="serviceType">Тип запрашиваемого сервиса</param>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
73 /// <returns>Объект, реализующий сервис</returns>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
74 /// <exception cref="KeyNotFoundException">Сервис не зарегистрирован</exception>
68
9dd6a896a385 ServiceLocator: small refactoring, GetService method is made virtual
cin
parents: 40
diff changeset
75 public object GetService(Type serviceType) {
69
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
76 object result;
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
77 if (TryGetService(serviceType, out result))
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
78 return result;
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
79 throw new ApplicationException (String.Format ("{0} doesn't provide {1} service", this, serviceType));
68
9dd6a896a385 ServiceLocator: small refactoring, GetService method is made virtual
cin
parents: 40
diff changeset
80 }
9dd6a896a385 ServiceLocator: small refactoring, GetService method is made virtual
cin
parents: 40
diff changeset
81
69
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
82 /// <summary>
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
83 /// Пытается получить требуемый сервис или совместимый с ним.
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
84 /// </summary>
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
85 /// <returns><c>true</c>, если сервис был найден, <c>false</c> в противном случае..</returns>
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
86 /// <param name="serviceType">Тип запрашиваемого сервиса.</param>
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
87 /// <param name="service">Искомый сервис.</param>
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
88 public virtual bool TryGetService(Type serviceType, out object service) {
86
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
89 Safe.ArgumentNotNull(serviceType, "serviceType");
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
90 AssertNotDisposed();
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
91
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
92 ServiceEntry se;
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
93 if (!m_services.TryGetValue(serviceType, out se)) {
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
94 // ищем ближайщий объект, реализующий нужный сервис
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
95 Type pt = null;
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
96 foreach (var t in m_services.Keys)
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
97 if (serviceType.IsAssignableFrom(t) && (pt == null || t.IsAssignableFrom(pt)))
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
98 pt = t;
69
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
99
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
100 if (pt == null) {
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
101 // нет нужного сервиса
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
102 service = null;
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
103 return false;
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
104 }
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
105
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
106 var pe = m_services[pt];
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
107
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
108 // найденная запись может ссылаться на оригинальную запись с сервисом
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
109 if(pe.origin != null) {
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
110 pt = pe.origin;
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
111 pe = m_services[pt];
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
112 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
113
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
114 // добавляем список с обратными ссылками
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
115 if (pe.associated == null)
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
116 pe.associated = new List<Type>();
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
117
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
118 pe.associated.Add(serviceType);
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
119
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
120 // обновляем родительскую запись
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
121 m_services[pt] = pe;
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
122
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
123 // создаем запись со ссылкой
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
124 se = new ServiceEntry {
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
125 service = pe.service,
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
126 origin = pt,
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
127 shared = true // предотвращаем множественные попытки освобождения
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
128 };
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
129
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
130 m_services[serviceType] = se;
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
131 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
132
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
133 // запись содержит в себе информацию о сервисе
69
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
134 if (se.service != null) {
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
135 service = se.service;
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
136 return true;
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
137 }
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
138
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
139 // текущая запись является ссылкой
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
140 if (se.origin != null) {
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
141 se.service = GetService(se.origin);
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
142 m_services[serviceType] = se;
69
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
143 service = se.service;
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
144 return true;
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
145 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
146
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
147 // текущая запись не является ссылкой и не имеет информации о сервисе
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
148 // она должна сожержать информацию об активации
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
149 if (se.activator != null) {
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
150 se.service = se.activator();
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
151
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
152 m_services[serviceType] = se;
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
153
69
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
154 service = se.service;
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
155 return true;
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
156 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
157
69
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
158 service = null;
48763f3b5db8 service locator refactoring
cin
parents: 68
diff changeset
159 return false;
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
160 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
161
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
162 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
163 /// Регистрирует фабрику для активации сервиса по первому требованию.
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
164 /// </summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
165 /// <typeparam name="T">Тип регистрируемого сервиса.</typeparam>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
166 /// <param name="activator">Фабрика для создания/получения объекта, предоставляющего сервис.</param>
86
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
167 /// <param name = "cleanup">Метод для освобождения экземпляра сервиса, будет вызыван при освобождении сервис-локатора.</param>
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
168 /// <exception cref="InvalidOperationException">Указанный сервис уже зарегистрирован.</exception>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
169 /// <remarks>При освобождении сервис-локатора, сервисы полученные в результате активации также будут освобождены.</remarks>
86
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
170 public void Register<T>(Func<T> activator, Action<T> cleanup) {
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
171 Safe.ArgumentNotNull(activator, "activator");
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
172
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
173 AssertNotDisposed();
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
174
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
175 Unregister(typeof(T));
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
176
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
177 m_services[typeof(T)] = new ServiceEntry {
86
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
178 activator = () => activator(),
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
179 cleanup = instance => cleanup((T)instance)
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
180 };
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
181 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
182
86
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
183 public void Register<T>(Func<T> activator) {
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
184 Register(activator, null);
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
185 }
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
186
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
187 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
188 /// Регистрирует объект, предоставляющий сервис.
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
189 /// </summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
190 /// <typeparam name="T">Тип регистрируемого сервиса.</typeparam>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
191 /// <param name="service">Объект, предоставляющий сервис.</param>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
192 /// <exception cref="InvalidOperationException">Указанный сервис уже зарегистрирован.</exception>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
193 /// <remarks>Сервис-локатором не управляет временем жизни объекта для зарегистрированного сервиса.</remarks>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
194 public void Register<T>(T service) {
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
195 Register(service, true);
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
196 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
197
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
198 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
199 /// Регистрирует объект, предоставляющий сервис.
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
200 /// </summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
201 /// <typeparam name="T">Тип регистрируемого сервиса.</typeparam>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
202 /// <param name="service">Объект, предоставляющий сервис.</param>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
203 /// <param name="shared">Признак того, что объект является разделяемым и сервис-локатор не должен его освобождать.</param>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
204 /// <exception cref="InvalidOperationException">Указанный сервис уже зарегистрирован.</exception>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
205 public void Register<T>(T service, bool shared) {
86
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
206 Safe.ArgumentNotNull(service, "service");
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
207
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
208 AssertNotDisposed();
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
209
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
210 Unregister(typeof(T));
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
211
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
212 m_services[typeof(T)] = new ServiceEntry { service = service, shared = shared };
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
213 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
214
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
215 public void Unregister(Type serviceType) {
86
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
216 Safe.ArgumentNotNull(serviceType, "serviceType");
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
217
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
218 AssertNotDisposed();
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
219
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
220 ServiceEntry se;
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
221 if (m_services.TryGetValue(serviceType, out se)) {
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
222 // освобождаем ресурсы
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
223 if (se.service != null && !se.shared)
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
224 ((IDisposable)se.service).Dispose();
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
225 m_services.Remove(serviceType);
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
226
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
227 // убираем связанные записи
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
228 if (se.associated != null)
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
229 foreach (var item in se.associated)
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
230 m_services.Remove(item);
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
231 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
232 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
233
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
234 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
235 /// Освобождает зарегистрированные сервисы (которые требуется освобоить).
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
236 /// </summary>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
237 /// <param name="disposing">Призанак того, что нужно освободить ресурсы.</param>
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
238 protected override void Dispose(bool disposing) {
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
239 if (disposing) {
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
240
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
241 foreach (var entry in m_services.Values)
86
b33832ab0262 ServiceLocator: added a cleanup callback to the service registration method
cin
parents: 69
diff changeset
242 entry.Dispose();
40
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
243
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
244 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
245 base.Dispose(disposing);
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
246 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
247 }
fe33f4e02ad5 improved tracing
cin
parents:
diff changeset
248 }