aboutsummaryrefslogtreecommitdiff
path: root/src/DI/container.hpp
blob: d5f52b899516ffe4e02b3dbef7e262abd2bb2441 (plain)
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
#pragma once

#include "DI/interfaces/wrapper.hpp"

#include "DI/concepts.hpp"
#include "DI/factory.hpp"
#include "DI/object_type.hpp"

#include <concepts>
#include <functional>
#include <memory>
#include <unordered_map>

class Container;

template <typename Interface>
class BindingBuilder
{
public:
	explicit BindingBuilder(Container *container) noexcept;

	template <typename Impl>
	requires Abstract<Interface> && std::derived_from<Impl, Interface>
	void to() noexcept;

	template <typename FactoryFunc>
	requires IsFactory<Interface> && std::constructible_from<Interface, FactoryFunc>
	void to_factory(FactoryFunc factory) noexcept;

private:
	Container *_container;
};

class Container
{
public:
	Container() noexcept = default;

	template <typename Type>
	using WrapperPtr = std::shared_ptr<Type>;

	template <class Interface>
	auto bind() noexcept -> BindingBuilder<Interface>;

	template <class Interface>
	requires Abstract<Interface>
	auto get() const noexcept -> std::unique_ptr<Interface>;

	template <typename AFactory>
	requires IsFactory<AFactory>
	auto get() const noexcept -> AFactory;

	void add(BaseObjectType type, const WrapperPtr<IGenericWrapper> &wrapper) noexcept;

private:
	std::unordered_map<BaseObjectType, WrapperPtr<IGenericWrapper>, ObjectTypeHasher>
		_bindings;
};

#include "container.tpp"