diff options
author | HampusM <hampus@hampusmat.com> | 2022-02-27 12:54:10 +0100 |
---|---|---|
committer | HampusM <hampus@hampusmat.com> | 2022-06-13 17:56:53 +0200 |
commit | 5864e5abc43b201c3801fa39a2fcaf9e3a9e8914 (patch) | |
tree | 98e5e324066ef4d1cbd3cc4c792a258fbd86c12d /src/DI/container.tpp | |
parent | e233dc28491c33e8a7dc0a11576d3b8ce91cce2c (diff) |
refactor: use dependency injection
Diffstat (limited to 'src/DI/container.tpp')
-rw-r--r-- | src/DI/container.tpp | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/src/DI/container.tpp b/src/DI/container.tpp new file mode 100644 index 0000000..21bf81a --- /dev/null +++ b/src/DI/container.tpp @@ -0,0 +1,53 @@ +#pragma once + +#include "container.hpp" + +#include "function_wrapper.hpp" +#include "object_wrapper.hpp" + +template <class Interface> +BindingBuilder<Interface>::BindingBuilder(Container *container) : _container(container) +{ +} + +template <class Interface> +template <class ObjectImpl, class> +void BindingBuilder<Interface>::to() +{ + _container->bindings.emplace( + ObjectType<Interface>(), + std::dynamic_pointer_cast<IGenericWrapper>( + std::make_shared<ObjectWrapper<Interface, ObjectImpl>>(*_container))); +} + +template <class Interface> +void BindingBuilder<Interface>::to_factory(Interface func) +{ + _container->bindings.emplace(ObjectType<Interface>(), + std::dynamic_pointer_cast<IGenericWrapper>( + std::make_shared<FunctionWrapper<Interface>>(func))); +} + +template <class Interface> +BindingBuilder<Interface> Container::bind() +{ + return BindingBuilder<Interface>(this); +} + +template <class Interface, class> +std::shared_ptr<Interface> Container::get() const +{ + auto wrapper = std::dynamic_pointer_cast<IWrapper<std::shared_ptr<Interface>>>( + bindings.at(ObjectType<Interface>())); + + return wrapper->get(); +} + +template <typename Interface, typename> +Interface Container::get() const +{ + auto wrapper = std::dynamic_pointer_cast<IWrapper<Interface>>( + bindings.at(ObjectType<Interface>())); + + return wrapper->get(); +} |