فهرست منبع

Add support for a limited-duration binding in the prototype factory in order to support injections for Unit Tests.

Sam Jaffe 6 سال پیش
والد
کامیت
1a2b220946
1فایلهای تغییر یافته به همراه15 افزوده شده و 0 حذف شده
  1. 15 0
      include/resource_factory/prototype_factory.hpp

+ 15 - 0
include/resource_factory/prototype_factory.hpp

@@ -45,9 +45,16 @@
 namespace objects { namespace prototype {
   template <typename Base, typename... Args>
   class factory {
+  private:
+    struct scoped_binding_t {
+      ~scoped_binding_t() { handle_->_factories.erase(name_); }
+      std::string name_;
+      factory * handle_;
+    };
   public:
     using rval_t = Base;
     using producer = std::function<rval_t(Args &&...)>;
+    using scoped_binding = std::unique_ptr<scoped_binding_t>;
     
     static factory & instance();
     
@@ -60,6 +67,14 @@ namespace objects { namespace prototype {
     bool bind(std::string const & type_id, producer p) {
       return _factories.insert(std::make_pair(type_id, p)).second;
     }
+    
+    // For Test Cases that require being able to set/re-set the binding
+    scoped_binding bind_scoped(std::string const & type_id, producer p) {
+      if (bind(type_id, p)) {
+        return scoped_binding(new scoped_binding_t{type_id, this});
+      }
+      return scoped_binding();
+    }
   private:
     factory() = default;
     std::unordered_map<std::string, producer> _factories;