Fabric: Support for optional `key` parameter to register/retrieve in ContextContainer
Summary: @public We need this in case when we want to store several intances of the same class in the container. Reviewed By: mdvacca Differential Revision: D8814808 fbshipit-source-id: 78ab15d78cf3878d03bf0a45bc42b968d87435e7
This commit is contained in:
parent
ec5b1fd259
commit
58da98149d
|
@ -24,20 +24,37 @@ using SharedContextContainer = std::shared_ptr<ContextContainer>;
|
||||||
class ContextContainer final {
|
class ContextContainer final {
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
/*
|
||||||
|
* Registers an instance of the particular type `T` in the container.
|
||||||
|
* If `key` parameter is specified, the instance is registered
|
||||||
|
* by `{type, key}` pair.
|
||||||
|
*/
|
||||||
template<typename T>
|
template<typename T>
|
||||||
void registerInstance(std::shared_ptr<T> instance) {
|
void registerInstance(std::shared_ptr<T> instance, const std::string &key = "") {
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
instances_.insert({std::type_index(typeid(T)), instance});
|
instances_.insert({
|
||||||
|
{std::type_index(typeid(T)), key},
|
||||||
|
instance
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns a previously registered instance of the particular type `T`.
|
||||||
|
* If `key` parameter is specified, the lookup will be performed
|
||||||
|
* by {type, key} pair.
|
||||||
|
*/
|
||||||
template<typename T>
|
template<typename T>
|
||||||
std::shared_ptr<T> getInstance() const {
|
std::shared_ptr<T> getInstance(const std::string &key = "") const {
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
return std::static_pointer_cast<T>(instances_.at(std::type_index(typeid(T))));
|
return std::static_pointer_cast<T>(instances_.at({std::type_index(typeid(T)), key}));
|
||||||
}
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
std::unordered_map<std::type_index, std::shared_ptr<void>> instances_;
|
std::unordered_map<
|
||||||
|
std::pair<std::type_index, std::string>,
|
||||||
|
std::shared_ptr<void>
|
||||||
|
> instances_;
|
||||||
|
|
||||||
mutable std::mutex mutex_;
|
mutable std::mutex mutex_;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue