/* * Copyright (C) 2021 Damir Porobic * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ /* * Implementation based on the Miniature IOC Container from phillipvoyle on codeproject.com, kudos to him. * Link: https://www.codeproject.com/Articles/1029836/A-Miniature-IOC-Container-in-Cplusplus */ #ifndef KSNIP_DEPENDENCYINJECTOR_H #define KSNIP_DEPENDENCYINJECTOR_H #include #include class DependencyInjector { private: static int NextTypeId; public: //one typeid per type template static int getTypeID() { static int typeId = NextTypeId++; return typeId; } class FactoryRoot { public: virtual ~FactoryRoot() = default; }; QMap> mFactories; template class CFactory: public FactoryRoot { private: std::function ()> mFunctor; public: ~CFactory() override = default; explicit CFactory(std::function ()> functor) : mFunctor(functor) { } QSharedPointer getObject() { return mFunctor(); } }; template QSharedPointer get() { auto typeId = getTypeID(); auto factoryBase = mFactories[typeId]; auto factory = qSharedPointerCast>(factoryBase); return factory->getObject(); } template void registerFunctor(std::function (QSharedPointer ...ts)> functor) { mFactories[getTypeID()] = QSharedPointer>::create([=]{ return functor(get()...); }); } // Register a single instance, always returns same instance, effectively single instance template void registerInstance(QSharedPointer t) { mFactories[getTypeID()] = QSharedPointer>::create([=]{ return t; }); } template void registerFunctor(QSharedPointer (*functor)(QSharedPointer ...ts)) { registerFunctor(std::function (QSharedPointer ...ts)>(functor)); } // Returns for every request a new instance template void registerFactory() { registerFunctor( std::function(QSharedPointer ...ts)>( [](QSharedPointer...arguments) -> QSharedPointer { return QSharedPointer::create(std::forward>(arguments)...); })); } template void registerInstance() { registerInstance(QSharedPointer::create(get()...)); } }; #endif //KSNIP_DEPENDENCYINJECTOR_H