2018-09-11 15:27:47 -07:00
|
|
|
// Copyright (c) Facebook, Inc. and its affiliates.
|
2018-06-22 07:28:34 -07:00
|
|
|
|
|
|
|
// This source code is licensed under the MIT license found in the
|
|
|
|
// LICENSE file in the root directory of this source tree.
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <memory>
|
|
|
|
#include <mutex>
|
2018-09-24 12:54:24 -07:00
|
|
|
#include <string>
|
2018-06-22 07:28:34 -07:00
|
|
|
#include <typeindex>
|
|
|
|
#include <typeinfo>
|
|
|
|
#include <unordered_map>
|
2018-09-24 12:54:24 -07:00
|
|
|
#include <utility>
|
2018-06-22 07:28:34 -07:00
|
|
|
|
|
|
|
namespace facebook {
|
|
|
|
namespace react {
|
|
|
|
|
|
|
|
class ContextContainer;
|
|
|
|
|
|
|
|
using SharedContextContainer = std::shared_ptr<ContextContainer>;
|
|
|
|
|
|
|
|
/*
|
|
|
|
* General purpose dependecy injection container.
|
2018-07-17 22:41:42 -07:00
|
|
|
* Instance types must be copyable.
|
2018-06-22 07:28:34 -07:00
|
|
|
*/
|
|
|
|
class ContextContainer final {
|
2018-10-09 16:25:13 -07:00
|
|
|
public:
|
2018-07-17 22:41:34 -07:00
|
|
|
/*
|
|
|
|
* Registers an instance of the particular type `T` in the container.
|
|
|
|
* If `key` parameter is specified, the instance is registered
|
|
|
|
* by `{type, key}` pair.
|
|
|
|
*/
|
2018-10-09 16:25:13 -07:00
|
|
|
template <typename T>
|
2018-09-24 12:54:24 -07:00
|
|
|
void registerInstance(const T &instance, const std::string &key = {}) {
|
2018-07-15 16:46:22 -07:00
|
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
2018-07-17 22:41:42 -07:00
|
|
|
|
2018-10-09 16:25:13 -07:00
|
|
|
instances_.insert(
|
|
|
|
{{std::type_index(typeid(T)), key}, std::make_shared<T>(instance)});
|
2018-07-15 16:46:22 -07:00
|
|
|
}
|
|
|
|
|
2018-07-17 22:41:34 -07:00
|
|
|
/*
|
|
|
|
* Returns a previously registered instance of the particular type `T`.
|
|
|
|
* If `key` parameter is specified, the lookup will be performed
|
|
|
|
* by {type, key} pair.
|
|
|
|
*/
|
2018-10-09 16:25:13 -07:00
|
|
|
template <typename T>
|
2018-09-24 12:54:24 -07:00
|
|
|
T getInstance(const std::string &key = {}) const {
|
2018-07-15 16:46:22 -07:00
|
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
2018-07-17 22:41:42 -07:00
|
|
|
|
2018-10-09 16:25:13 -07:00
|
|
|
return *std::static_pointer_cast<T>(
|
|
|
|
instances_.at({std::type_index(typeid(T)), key}));
|
2018-07-15 16:46:22 -07:00
|
|
|
}
|
2018-06-22 07:28:34 -07:00
|
|
|
|
2018-10-09 16:25:13 -07:00
|
|
|
private:
|
2018-07-17 22:41:34 -07:00
|
|
|
std::unordered_map<
|
2018-10-09 16:25:13 -07:00
|
|
|
std::pair<std::type_index, std::string>,
|
|
|
|
std::shared_ptr<void>>
|
|
|
|
instances_;
|
2018-07-17 22:41:34 -07:00
|
|
|
|
2018-06-22 07:28:34 -07:00
|
|
|
mutable std::mutex mutex_;
|
|
|
|
};
|
|
|
|
|
|
|
|
} // namespace react
|
|
|
|
} // namespace facebook
|