Skip to content

Commit

Permalink
Fabric: ContextContainer is now able to store any copyable values
Browse files Browse the repository at this point in the history
Summary:
@public
Previously, ContextContainer could store only `shared_ptr`s, but now it wraps all values in own `shared_ptr` container.
I wish we can use `unique_ptr` here, but apparently we cannot because `unique_ptr` does not support type-erasure (`std::unique_ptr<void>` is illigal).
Becasue ContextContainer is not supposed to be used in hot paths, the performance aspect of that does not actually matter.

Reviewed By: mdvacca

Differential Revision: D8853446

fbshipit-source-id: e5d0a5595fe44c59f1395d6ffccf9d3fed923c83
  • Loading branch information
shergin authored and facebook-github-bot committed Jul 18, 2018
1 parent 07a4a95 commit 9395485
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class ImageComponentDescriptor final:
public:
ImageComponentDescriptor(SharedEventDispatcher eventDispatcher, const SharedContextContainer &contextContainer):
ConcreteComponentDescriptor(eventDispatcher),
imageManager_(contextContainer->getInstance<ImageManager>()) {}
imageManager_(contextContainer->getInstance<SharedImageManager>()) {}

void adopt(UnsharedShadowNode shadowNode) const override {
ConcreteComponentDescriptor::adopt(shadowNode);
Expand Down
11 changes: 7 additions & 4 deletions ReactCommon/fabric/uimanager/ContextContainer.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ using SharedContextContainer = std::shared_ptr<ContextContainer>;

/*
* General purpose dependecy injection container.
* Instance types must be copyable.
*/
class ContextContainer final {

Expand All @@ -30,11 +31,12 @@ class ContextContainer final {
* by `{type, key}` pair.
*/
template<typename T>
void registerInstance(std::shared_ptr<T> instance, const std::string &key = "") {
void registerInstance(const T &instance, const std::string &key = "") {
std::lock_guard<std::mutex> lock(mutex_);

instances_.insert({
{std::type_index(typeid(T)), key},
instance
std::make_shared<T>(instance)
});
}

Expand All @@ -44,9 +46,10 @@ class ContextContainer final {
* by {type, key} pair.
*/
template<typename T>
std::shared_ptr<T> getInstance(const std::string &key = "") const {
T getInstance(const std::string &key = "") const {
std::lock_guard<std::mutex> lock(mutex_);
return std::static_pointer_cast<T>(instances_.at({std::type_index(typeid(T)), key}));

return *std::static_pointer_cast<T>(instances_.at({std::type_index(typeid(T)), key}));
}

private:
Expand Down

0 comments on commit 9395485

Please sign in to comment.