IOC简介

IOC全称为Inversion of Control,即控制反转。

控制反转是一种设计思想,而不是一个具体的技术实现。这种设计思想用大白话解释就是“我们想要什么就自己拿什么,而不是看给什么”

一种设计思想可以有多种方式去实现,其中最常见的一个实现方式是DI。

DI

DI,全称为Dependency Injection,即依赖注入。

依赖这个概念,我们在对象之间的交互里接触过,当时说过一种单向依赖,即自顶向下的依赖。具体是:父节点持有子节点的对象。

1
2
3
4
public class A
{
public B b = new B();
}

我们可以说A依赖B,这就是关于依赖的意思,可以理解成持有另一个对象的引用或者在方法中获取另一个对象。

注入的意思,我们通过下面的代码体会:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class A
{
public B b = null;
}
public class B {}

void Main()
{
var a = new A();
var b = new B();

a.b = b;
}

a的成员变量是在外部设置对象的,即a.b=b,而a.b=b这个过程就是注入过程。注入过程就是给目标对象传值或目标对象内部方法传值,这个例子只是为了解释注入的概念,这里面并没有体现“我们想要什么就自己拿什么,而不是看给什么”,我们接着深入。

IOCKit

在所有的DI方案中,都有一个容器的概念。有的时候DI容器也叫做IOC容器(IOCContainer或DIContainer)。它用来储存实例和引用,在给对象的成员变量(引用)设置值时使用这个容器储存的实例。

我们使用QFramework的IOCKit,看一下具体使用代码是什么样子的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
/****************************************************************************
* Copyright (c) 2018 ~ 2022 liangxiegame UNDER MIT License
*
* http://qframework.io
* https://github.com/liangxiegame/QFramework
****************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace QFramework
{
/// <summary>
/// Used by the injection container to determine if a property or field should be injected.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class InjectAttribute : Attribute
{
public InjectAttribute(string name)
{
Name = name;
}

public string Name { get; set; }

public InjectAttribute()
{
}
}

public interface IQFrameworkContainer
{
/// <summary>
/// Clears all type mappings and instances.
/// </summary>
void Clear();

/// <summary>
/// Injects registered types/mappings into an object
/// </summary>
/// <param name="obj"></param>
void Inject(object obj);

/// <summary>
/// Injects everything that is registered at once
/// </summary>
void InjectAll();

/// <summary>
/// Register a type mapping
/// </summary>
/// <typeparam name="TSource">The base type.</typeparam>
/// <typeparam name="TTarget">The concrete type</typeparam>
void Register<TSource, TTarget>(string name = null);

void RegisterRelation<TFor, TBase, TConcrete>();

/// <summary>
/// Register an instance of a type.
/// </summary>
/// <typeparam name="TBase"></typeparam>
/// <param name="default"></param>
/// <param name="injectNow"></param>
/// <returns></returns>
void RegisterInstance<TBase>(TBase @default, bool injectNow) where TBase : class;

/// <summary>
/// Register an instance of a type.
/// </summary>
/// <param name="type"></param>
/// <param name="default"></param>
/// <param name="injectNow"></param>
/// <returns></returns>
void RegisterInstance(Type type, object @default, bool injectNow);

/// <summary>
/// Register a named instance
/// </summary>
/// <param name="baseType">The type to register the instance for.</param>
/// <param name="name">The name for the instance to be resolved.</param>
/// <param name="instance">The instance that will be resolved be the name</param>
/// <param name="injectNow">Perform the injection immediately</param>
void RegisterInstance(Type baseType, object instance = null, string name = null, bool injectNow = true);

void RegisterInstance<TBase>(TBase instance, string name, bool injectNow = true) where TBase : class;

void RegisterInstance<TBase>(TBase instance) where TBase : class;

/// <summary>
/// If an instance of T exist then it will return that instance otherwise it will create a new one based off mappings.
/// </summary>
/// <typeparam name="T">The type of instance to resolve</typeparam>
/// <returns>The/An instance of 'instanceType'</returns>
T Resolve<T>(string name = null, bool requireInstance = false, params object[] args) where T : class;

TBase ResolveRelation<TBase>(Type tfor, params object[] arg);

TBase ResolveRelation<TFor, TBase>(params object[] arg);

/// <summary>
/// Resolves all instances of TType or subclasses of TType. Either named or not.
/// </summary>
/// <typeparam name="TType">The Type to resolve</typeparam>
/// <returns>List of objects.</returns>
IEnumerable<TType> ResolveAll<TType>();

//IEnumerable<object> ResolveAll(Type type);
void Register(Type source, Type target, string name = null);

/// <summary>
/// Resolves all instances of TType or subclasses of TType. Either named or not.
/// </summary>
/// <typeparam name="TType">The Type to resolve</typeparam>
/// <returns>List of objects.</returns>
IEnumerable<object> ResolveAll(Type type);

TypeMappingCollection Mappings { get; set; }
TypeInstanceCollection Instances { get; set; }
TypeRelationCollection RelationshipMappings { get; set; }

/// <summary>
/// If an instance of instanceType exist then it will return that instance otherwise it will create a new one based off mappings.
/// </summary>
/// <param name="baseType">The type of instance to resolve</param>
/// <param name="name">The type of instance to resolve</param>
/// <param name="requireInstance">If true will return null if an instance isn't registered.</param>
/// <returns>The/An instance of 'instanceType'</returns>
object Resolve(Type baseType, string name = null, bool requireInstance = false,
params object[] constructorArgs);

object ResolveRelation(Type tfor, Type tbase, params object[] arg);
void RegisterRelation(Type tfor, Type tbase, Type tconcrete);
object CreateInstance(Type type, params object[] args);
}

/// <summary>
/// A ViewModel Container and a factory for Controllers and commands.
/// </summary>

public class QFrameworkContainer : IQFrameworkContainer
{
private TypeInstanceCollection _instances;
private TypeMappingCollection _mappings;


public TypeMappingCollection Mappings
{
get { return _mappings ?? (_mappings = new TypeMappingCollection()); }
set { _mappings = value; }
}

public TypeInstanceCollection Instances
{
get { return _instances ?? (_instances = new TypeInstanceCollection()); }
set { _instances = value; }
}

public TypeRelationCollection RelationshipMappings
{
get { return _relationshipMappings; }
set { _relationshipMappings = value; }
}

public IEnumerable<TType> ResolveAll<TType>()
{
foreach (var obj in ResolveAll(typeof(TType)))
{
yield return (TType) obj;
}
}

/// <summary>
/// Resolves all instances of TType or subclasses of TType. Either named or not.
/// </summary>
/// <typeparam name="TType">The Type to resolve</typeparam>
/// <returns>List of objects.</returns>
public IEnumerable<object> ResolveAll(Type type)
{
foreach (KeyValuePair<Tuple<Type, string>, object> kv in Instances)
{
if (kv.Key.Item1 == type && !string.IsNullOrEmpty(kv.Key.Item2))
yield return kv.Value;
}

foreach (KeyValuePair<Tuple<Type, string>, Type> kv in Mappings)
{
if (!string.IsNullOrEmpty(kv.Key.Item2))
{
#if NETFX_CORE
var condition = type.GetTypeInfo().IsSubclassOf(mapping.From);
#else
var condition = type.IsAssignableFrom(kv.Key.Item1);
#endif
if (condition)
{
var item = Activator.CreateInstance(kv.Value);
Inject(item);
yield return item;
}
}
}
}

/// <summary>
/// Clears all type-mappings and instances.
/// </summary>
public void Clear()
{
Instances.Clear();
Mappings.Clear();
RelationshipMappings.Clear();
}

/// <summary>
/// Injects registered types/mappings into an object
/// </summary>
/// <param name="obj"></param>
public void Inject(object obj)
{
if (obj == null) return;
#if !NETFX_CORE
var members = obj.GetType().GetMembers();
#else
var members = obj.GetType().GetTypeInfo().DeclaredMembers;
#endif
foreach (var memberInfo in members)
{
var injectAttribute =
memberInfo.GetCustomAttributes(typeof(InjectAttribute), true).FirstOrDefault() as InjectAttribute;
if (injectAttribute != null)
{
if (memberInfo is PropertyInfo)
{
var propertyInfo = memberInfo as PropertyInfo;
propertyInfo.SetValue(obj, Resolve(propertyInfo.PropertyType, injectAttribute.Name), null);
}
else if (memberInfo is FieldInfo)
{
var fieldInfo = memberInfo as FieldInfo;
fieldInfo.SetValue(obj, Resolve(fieldInfo.FieldType, injectAttribute.Name));
}
}
}
}

/// <summary>
/// Register a type mapping
/// </summary>
/// <typeparam name="TSource">The base type.</typeparam>
/// <typeparam name="TTarget">The concrete type</typeparam>
public void Register<TSource>(string name = null)
{
Mappings[typeof(TSource), name] = typeof(TSource);
}


/// <summary>
/// Register a type mapping
/// </summary>
/// <typeparam name="TSource">The base type.</typeparam>
/// <typeparam name="TTarget">The concrete type</typeparam>
public void Register<TSource, TTarget>(string name = null)
{
Mappings[typeof(TSource), name] = typeof(TTarget);
}

public void Register(Type source, Type target, string name = null)
{
Mappings[source, name] = target;
}

/// <summary>
/// Register a named instance
/// </summary>
/// <param name="baseType">The type to register the instance for.</param>
/// <param name="instance">The instance that will be resolved be the name</param>
/// <param name="injectNow">Perform the injection immediately</param>
public void RegisterInstance(Type baseType, object instance = null, bool injectNow = true)
{
RegisterInstance(baseType, instance, null, injectNow);
}

/// <summary>
/// Register a named instance
/// </summary>
/// <param name="baseType">The type to register the instance for.</param>
/// <param name="name">The name for the instance to be resolved.</param>
/// <param name="instance">The instance that will be resolved be the name</param>
/// <param name="injectNow">Perform the injection immediately</param>
public virtual void RegisterInstance(Type baseType, object instance = null, string name = null,
bool injectNow = true)
{
Instances[baseType, name] = instance;
if (injectNow)
{
Inject(instance);
}
}

public void RegisterInstance<TBase>(TBase instance) where TBase : class
{
RegisterInstance<TBase>(instance, true);
}

public void RegisterInstance<TBase>(TBase instance, bool injectNow) where TBase : class
{
RegisterInstance<TBase>(instance, null, injectNow);
}

public void RegisterInstance<TBase>(TBase instance, string name, bool injectNow = true) where TBase : class
{
RegisterInstance(typeof(TBase), instance, name, injectNow);
}

/// <summary>
/// If an instance of T exist then it will return that instance otherwise it will create a new one based off mappings.
/// </summary>
/// <typeparam name="T">The type of instance to resolve</typeparam>
/// <returns>The/An instance of 'instanceType'</returns>
public T Resolve<T>(string name = null, bool requireInstance = false, params object[] args) where T : class
{
return (T) Resolve(typeof(T), name, requireInstance, args);
}

/// <summary>
/// If an instance of instanceType exist then it will return that instance otherwise it will create a new one based off mappings.
/// </summary>
/// <param name="baseType">The type of instance to resolve</param>
/// <param name="name">The type of instance to resolve</param>
/// <param name="requireInstance">If true will return null if an instance isn't registered.</param>
/// <param name="constructorArgs">The arguments to pass to the constructor if any.</param>
/// <returns>The/An instance of 'instanceType'</returns>
public object Resolve(Type baseType, string name = null, bool requireInstance = false,
params object[] constructorArgs)
{
// Look for an instance first
var item = Instances[baseType, name];
if (item != null)
{
return item;
}

if (requireInstance)
return null;
// Check if there is a mapping of the type
var namedMapping = Mappings[baseType, name];
if (namedMapping != null)
{
var obj = CreateInstance(namedMapping, constructorArgs);
//Inject(obj);
return obj;
}

return null;
}

public object CreateInstance(Type type, params object[] constructorArgs)
{
if (constructorArgs != null && constructorArgs.Length > 0)
{
//return Activator.CreateInstance(type,BindingFlags.Public | BindingFlags.Instance,Type.DefaultBinder, constructorArgs,CultureInfo.CurrentCulture);
var obj2 = Activator.CreateInstance(type, constructorArgs);
Inject(obj2);
return obj2;
}
#if !NETFX_CORE
ConstructorInfo[] constructor = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
#else
ConstructorInfo[] constructor = type.GetTypeInfo().DeclaredConstructors.ToArray();
#endif

if (constructor.Length < 1)
{
var obj2 = Activator.CreateInstance(type);
Inject(obj2);
return obj2;
}

var maxParameters = constructor.First().GetParameters();

foreach (var c in constructor)
{
var parameters = c.GetParameters();
if (parameters.Length > maxParameters.Length)
{
maxParameters = parameters;
}

}

var args = maxParameters.Select(p =>
{
if (p.ParameterType.IsArray)
{
return ResolveAll(p.ParameterType);
}

return Resolve(p.ParameterType) ?? Resolve(p.ParameterType, p.Name);
}).ToArray();

var obj = Activator.CreateInstance(type, args);
Inject(obj);
return obj;
}

public TBase ResolveRelation<TBase>(Type tfor, params object[] args)
{
try
{
return (TBase) ResolveRelation(tfor, typeof(TBase), args);
}
catch (InvalidCastException castIssue)
{
throw new Exception(
string.Format("Resolve Relation couldn't cast to {0} from {1}", typeof(TBase).Name, tfor.Name),
castIssue);
}
}

public void InjectAll()
{
foreach (object instance in Instances.Values)
{
Inject(instance);
}
}

private TypeRelationCollection _relationshipMappings = new TypeRelationCollection();

public void RegisterRelation<TFor, TBase, TConcrete>()
{
RelationshipMappings[typeof(TFor), typeof(TBase)] = typeof(TConcrete);
}

public void RegisterRelation(Type tfor, Type tbase, Type tconcrete)
{
RelationshipMappings[tfor, tbase] = tconcrete;
}

public object ResolveRelation(Type tfor, Type tbase, params object[] args)
{
var concreteType = RelationshipMappings[tfor, tbase];

if (concreteType == null)
{
return null;
}

var result = CreateInstance(concreteType, args);
//Inject(result);
return result;
}

public TBase ResolveRelation<TFor, TBase>(params object[] arg)
{
return (TBase) ResolveRelation(typeof(TFor), typeof(TBase), arg);
}
}

// http://stackoverflow.com/questions/1171812/multi-key-dictionary-in-c
public class Tuple<T1, T2> //FUCKING Unity: struct is not supported in Mono
{
public readonly T1 Item1;
public readonly T2 Item2;

public Tuple(T1 item1, T2 item2)
{
Item1 = item1;
Item2 = item2;
}

public override bool Equals(Object obj)
{
Tuple<T1, T2> p = obj as Tuple<T1, T2>;
if (obj == null) return false;

if (Item1 == null)
{
if (p.Item1 != null) return false;
}
else
{
if (p.Item1 == null || !Item1.Equals(p.Item1)) return false;
}

if (Item2 == null)
{
if (p.Item2 != null) return false;
}
else
{
if (p.Item2 == null || !Item2.Equals(p.Item2)) return false;
}

return true;
}

public override int GetHashCode()
{
int hash = 0;
if (Item1 != null)
hash ^= Item1.GetHashCode();
if (Item2 != null)
hash ^= Item2.GetHashCode();
return hash;
}
}

// Kanglai: Using Dictionary rather than List!
public class TypeMappingCollection : Dictionary<Tuple<Type, string>, Type>
{
public Type this[Type from, string name = null]
{
get
{
Tuple<Type, string> key = new Tuple<Type, string>(from, name);
Type mapping = null;
if (this.TryGetValue(key, out mapping))
{
return mapping;
}

return null;
}
set
{
Tuple<Type, string> key = new Tuple<Type, string>(from, name);
this[key] = value;
}
}
}

public class TypeInstanceCollection : Dictionary<Tuple<Type, string>, object>
{

public object this[Type from, string name = null]
{
get
{
Tuple<Type, string> key = new Tuple<Type, string>(from, name);
object mapping = null;
if (this.TryGetValue(key, out mapping))
{
return mapping;
}

return null;
}
set
{
Tuple<Type, string> key = new Tuple<Type, string>(from, name);
this[key] = value;
}
}
}

public class TypeRelationCollection : Dictionary<Tuple<Type, Type>, Type>
{

public Type this[Type from, Type to]
{
get
{
Tuple<Type, Type> key = new Tuple<Type, Type>(from, to);
Type mapping = null;
if (this.TryGetValue(key, out mapping))
{
return mapping;
}

return null;
}
set
{
Tuple<Type, Type> key = new Tuple<Type, Type>(from, to);
this[key] = value;
}
}
}
}

IOCKit使用

在Unity中新建一个项目,新建一个脚本命名为IOCKit,将上面的代码粘贴进来。

再新建一个脚本,命名为IOCKitExample

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using UnityEngine;
using QFramework;

namespace IOCExample
{
public class ServiceA
{
public void Say()
{
Debug.Log("Say Hello");
}
}

public class IOCKitExample : MonoBehaviour
{
[Inject]//标记要注入的引用
public ServiceA AserviceObject {get;set;}

void Start()
{
var container = new QFrameworkContainer();
container.Register<ServiceA>();//使用注册方法,在容器内生成一个实例,并对应type的key
container.Inject(this);//通过反射获取此类中拥有[Inject]特性的属性,调用Resolve方法并在container中查找此属性的type对应的实例赋给这个属性
AserviceObject.Say();
}
}
}

IOCKit注入过程

在第一季决定版架构中,使用的IOCContainer,是一个非常简化版本的容器,砍掉了依赖注入功能,因为依赖注入功能使用了反射,反射对性能的影响比较大。

下一节介绍IOC的优点。