1
|
1 |
|
import inspect |
2
|
|
|
|
3
|
|
|
|
4
|
1 |
|
class Service(object): |
5
|
|
|
""" |
6
|
|
|
A service represents a class that the dependency injector can instantiate when asked. |
7
|
|
|
|
8
|
|
|
After the service has been declared, its arguments might be specified |
9
|
|
|
using the methods add_argument or add_arguments. |
10
|
|
|
The argument value can be: |
11
|
|
|
* A raw value that will be injected as it is when instantiating the service |
12
|
|
|
* A reference to another service. This reference service will be instantiated |
13
|
|
|
before being injected during the service instantiation |
14
|
|
|
""" |
15
|
|
|
|
16
|
1 |
|
def __init__(self, subject): |
17
|
1 |
|
self._subject = subject |
18
|
1 |
|
self._arguments = dict() |
19
|
1 |
|
self._is_singleton = False |
20
|
1 |
|
self._type = "instance" |
21
|
1 |
|
if inspect.isclass(subject) is True: |
22
|
1 |
|
self._type = "class" |
23
|
|
|
|
24
|
1 |
|
@property |
25
|
|
|
def type(self): |
26
|
1 |
|
return self._type |
27
|
|
|
|
28
|
1 |
|
@property |
29
|
|
|
def is_singleton(self): |
30
|
|
|
""" |
31
|
|
|
Get whether this service is a Singleton or not |
32
|
|
|
""" |
33
|
1 |
|
return self._is_singleton |
34
|
|
|
|
35
|
1 |
|
@is_singleton.setter |
36
|
|
|
def is_singleton(self, value): |
37
|
|
|
""" |
38
|
|
|
Set whether this service is a Singleton or not |
39
|
|
|
""" |
40
|
1 |
|
self._is_singleton = value |
41
|
|
|
|
42
|
1 |
|
@property |
43
|
|
|
def subject(self): |
44
|
|
|
""" |
45
|
|
|
Subject of this service |
46
|
|
|
|
47
|
|
|
The subject might be a class that will be instantiated |
48
|
|
|
or an instance that just will be returned |
49
|
|
|
""" |
50
|
1 |
|
return self._subject |
51
|
|
|
|
52
|
1 |
|
@property |
53
|
|
|
def arguments(self): |
54
|
|
|
""" |
55
|
|
|
Arguments of this service |
56
|
|
|
|
57
|
|
|
:rtype: dict |
58
|
|
|
""" |
59
|
1 |
|
return self._arguments |
60
|
|
|
|
61
|
1 |
|
def add_argument(self, name, value): |
62
|
|
|
""" |
63
|
|
|
Add an argument to this service |
64
|
|
|
|
65
|
|
|
The argument value can be a reference to another service. |
66
|
|
|
In this case the reference service will be instantiated |
67
|
|
|
before being injected in this service |
68
|
|
|
|
69
|
|
|
:param name: Name of the argument to add |
70
|
|
|
:param value: Value to assign to the argument |
71
|
|
|
:type name: string |
72
|
|
|
:type value: mixed |
73
|
|
|
:return: The service |
74
|
|
|
:rtype: Service |
75
|
|
|
""" |
76
|
1 |
|
self._arguments[name] = value |
77
|
1 |
|
return self |
78
|
|
|
|
79
|
1 |
|
def add_arguments(self, **kwargs): |
80
|
|
|
""" |
81
|
|
|
Add several arguments to this service. |
82
|
|
|
""" |
83
|
1 |
|
self._arguments.update(kwargs) |
84
|
|
|
return self |
85
|
|
|
|