/
NestedRegistrationScope.h
75 lines (57 loc) · 2.08 KB
/
NestedRegistrationScope.h
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
#pragma once
#include <memory>
#include <mutex>
#include <vector>
#include "Hypodermic/IRegistration.h"
#include "Hypodermic/RegistrationScope.h"
#include "Hypodermic/TypeAliasKey.h"
namespace Hypodermic
{
class NestedRegistrationScope : public IRegistrationScope, public std::enable_shared_from_this< NestedRegistrationScope >
{
public:
explicit NestedRegistrationScope(const std::shared_ptr< IRegistrationScope >& parentScope)
: m_parentScope(parentScope)
{
}
void addRegistration(const std::shared_ptr< IRegistration >& registration) override
{
writeScope().addRegistration(registration);
}
bool tryGetRegistrations(const TypeAliasKey& typeAliasKey, std::vector< std::shared_ptr< RegistrationContext > >& registrationContexts) const override
{
return scope().tryGetRegistrations(typeAliasKey, registrationContexts);
}
void copyTo(IRegistrationScope& other) const override
{
std::lock_guard< decltype(m_mutex) > lock(m_mutex);
scope().copyTo(other);
}
void addRegistrationContext(const std::shared_ptr< RegistrationContext >& registrationContext) override
{
writeScope().addRegistrationContext(registrationContext);
}
private:
IRegistrationScope& scope() const
{
std::lock_guard< decltype(m_mutex) > lock(m_mutex);
if (m_scope != nullptr)
return *m_scope;
return *m_parentScope;
}
IRegistrationScope& writeScope()
{
std::lock_guard< decltype(m_mutex) > lock(m_mutex);
if (m_scope == nullptr)
{
m_scope = std::make_shared< RegistrationScope >();
m_parentScope->copyTo(*m_scope);
}
return *m_scope;
}
private:
std::shared_ptr< IRegistrationScope > m_parentScope;
std::shared_ptr< RegistrationScope > m_scope;
mutable std::recursive_mutex m_mutex;
};
} // namespace Hypodermic