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