-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathDIFactory.hxx
103 lines (83 loc) · 3.16 KB
/
DIFactory.hxx
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
/*
* DIFactory.hxx
*
* Created on: Oct 23, 2021
* Author: <a href="mailto:[email protected]">Damir Ljubic</a>
*/
#ifndef DI_DIFACTORY_HXX_
#define DI_DIFACTORY_HXX_
#include <tuple>
#include <iostream>
#include <type_traits>
#include "Factory.hxx"
namespace utils::di
{
template <typename T>
struct IFactory
{
virtual ~IFactory() = default;
virtual std::unique_ptr<T> create() = 0;
protected:
IFactory() = default;
};
template <typename DIServiceInterface, typename DIService, typename...Args>
class DIFactory final : IFactory<DIServiceInterface>
{
static_assert(std::is_base_of_v<DIServiceInterface, DIService>, "DI: Invalid service implementation!");
public:
static auto createFactory(Args&&...args)
{
return std::unique_ptr<IFactory<DIServiceInterface>>(new (std::nothrow)
DIFactory(std::forward<Args>(args)...));
}
/**
* Factory method: creates the dependency object, a
* Service that will be injected at client side.
*
* @return Reference to the service concrete implementation upcasted
* to the matching interface
*
* @note template <class T> class A{ public: A(T* t);};
* There is no hierarchy relationship between A<Base> and A<Derived> instances
* (only between template parameters)
*/
std::unique_ptr<DIServiceInterface> create() override
{
return std::apply(
[](auto&&...args)
{
return factory<DIService>(std::forward<decltype(args)>(args)...);
}
, m_args);
}
~DIFactory() override = default;
// Copy-operations forbidden
DIFactory(const DIFactory&) = delete;
DIFactory& operator=(const DIFactory&) = delete;
private:
/**
* For binding the arguments of dependency object - service creation,
* with factory method
*
* <p>
* The service factory will be placed into IOC container.
* In case that expectation is that each call of the @see DIFactory#create
* creates the new instance of the service implementation, to accomplish that,
* the arguments for the factory function need to be stored into tuple
*
* @param args Service implementation construction arguments
*/
explicit DIFactory(Args&&...args) noexcept :
m_args(std::make_tuple(std::forward<Args>(args)...))
{}
private:
std::tuple<std::decay_t<Args>...> m_args; // store the arguments
};
template <typename DIServiceInterface, typename DIService, typename...Args>
auto make_factory(Args&&...args) noexcept
{
return DIFactory<DIServiceInterface, DIService, Args...>::createFactory(
std::forward<Args>(args)...);
}
}
#endif /* DI_DIFACTORY_HXX_ */