Autowiring  1.0.3
A C++ Inversion of Control Framework
CoreContext Class Reference

A top-level container class representing an autowiring domain, a minimum broadcast domain, and a thread execution domain. More...

#include <CoreContext.h>

Inheritance diagram for CoreContext:
CoreContextT< T > CoreContextT< GlobalCoreContext > GlobalCoreContext

Public Member Functions

template<typename T >
void Add (const std::shared_ptr< T > &ptr)
 Introduces the specified pointer to this context explicitly More...
 
void AddSnooper (const autowiring::CoreObjectDescriptor &traits)
 Runtime version of AddSnooper More...
 
template<class T >
void AddSnooper (const std::shared_ptr< T > &pSnooper)
 Registers the specified event receiver to receive messages from this context More...
 
template<class T >
void AddSnooper (const Autowired< T > &snooper)
 Resolution overload More...
 
template<typename T >
const std::shared_ptr< T > & Await (void)
 Similar to Inject, except will block until the specified type is available in the context More...
 
template<typename T >
std::shared_ptr< T > Await (std::chrono::nanoseconds timeout)
 Timed version of Await More...
 
const AnySharedPointer & Await (auto_id id)
 Runtime Await variant More...
 
AnySharedPointer Await (auto_id id, std::chrono::nanoseconds timeout)
 Runtime Await variant More...
 
template<class T , class... Sigils>
void BoltTo (void)
 Injects the specified type T into all subcontexts created with one of the matching sigil types. More...
 
std::vector< const autowiring::CoreObjectDescriptor * > BuildObjectState (void) const
 Gets a snapshot of all of the objects currently in the context More...
 
std::vector< std::shared_ptr< BasicThread > > CopyBasicThreadList (void) const
 A copy of the current list of child CoreRunnables of this context. More...
 
template<class T >
std::shared_ptr< CoreContextT< T > > Create (void)
 Creates a child context of this context. More...
 
bool DelayUntilInitiated (void)
 Waits until the context is initiated or, if never initiated, until it starts shutting down. More...
 
void Dump (std::ostream &os) const
 Utility debug method for writing a snapshot of this context to the specified output stream More...
 
template<class T >
void Enable (void)
 Allows a specifically named class to be "bolted" to this context or one of its subcontexts. More...
 
void FilterException (void)
 Filters std::current_exception using any registered exception filters, or rethrows. More...
 
void FilterFiringException (const JunctionBoxBase *pProxy, CoreObject *pRecipient)
 Filters a std::current_exception thrown by an EventSenderBase during a Fire More...
 
std::shared_ptr< CoreContextFirstChild (void) const
 The first child in the set of this context's children. More...
 
auto_id GetAutoTypeId (const AnySharedPointer &ptr) const
 Gets the type information for the instance referenced by the specified shared pointer. More...
 
t_childList::iterator GetBackReference (void) const
 The Context iterator for the parent context's children, pointing to this context.
 
size_t GetChildCount (void) const
 The number of child contexts of this context.
 
size_t GetMemberCount (void) const
 The number of Autowired members in this context.
 
const std::shared_ptr< CoreContext > & GetParentContext (void) const
 A shared reference to the parent context of this context.
 
std::vector< CoreRunnable * > GetRunnables (void) const
 Returns a copy of the list of runnables More...
 
auto_id GetSigilType (void) const
 The type used as a sigil when creating this class, if any.
 
template<class T >
bool Has (void) const
 True, if an instance of the specified type exists and dependencies of that type can be autowired in this context. More...
 
void Initiate (void)
 Starts all registered threads and enables events and the flow of filter graph packets. More...
 
template<typename T , typename... Args>
std::shared_ptr< T > Inject (Args &&...args)
 Injects the specified types into this context. More...
 
template<class Sigil >
bool Is (void) const
 True if the sigil type of this CoreContext matches the specified sigil type.
 
bool IsAncestorOf (const CoreContext *child) const
 Reports whether the specified context is an ancestor of this context. More...
 
bool IsAnonymousContext (void) const
 True if and only if this is an anonymous context.
 
bool IsGlobalContext (void) const
 True if and only if this is the global context.
 
bool IsInitiated (void) const
 True, if the context has been initiated. More...
 
bool IsQuiescent (void) const
 Retrieves the system's current quiescence status More...
 
bool IsRunning (void) const
 True, if the context is presently running. More...
 
bool IsShutdown (void) const
 
std::shared_ptr< CoreContextNextSibling (void) const
 The next context sharing the same parent, or null if this is the last entry in the list More...
 
template<class T , class Fn >
void NotifyWhenAutowired (Fn &&listener)
 Adds a post-attachment listener in this context for a particular autowired member. There is no guarantee for the context in which the listener will be called. More...
 
void Quiescent (void) const
 Identical to Wait, except blocks only until the threads in this and all descendant contexts have stopped More...
 
bool Quiescent (std::chrono::nanoseconds duration) const
 Timed version of Quiescent More...
 
void RemoveSnooper (const autowiring::CoreObjectDescriptor &traits)
 Runtime version of RemoveSnooper More...
 
template<class T >
void RemoveSnooper (const std::shared_ptr< T > &pSnooper)
 Unregisters a snooper previously registered to receive snooped events More...
 
template<class T >
void RemoveSnooper (const Autowired< T > &snooper)
 Resolution overload of RemoveSnooper More...
 
std::shared_ptr< CoreContextSetCurrent (void)
 Makes this context the current context. More...
 
void SetUnlinkOnTeardown (bool unlinkOnTeardown)
 Sets the context's teardown unlink behavior More...
 
void SignalShutdown (bool wait=false, ShutdownMode shutdownMode=ShutdownMode::Graceful)
 Begins shutdown of this context, optionally waiting for child contexts and threads to also shut down before returning. More...
 
void SignalTerminate (bool wait=true)
 Shuts down the context with the Immediate shutdown mode. More...
 
void Wait (void)
 Waits until the context begins shutting down (IsShutdown is true) and all threads and child threads have terminated. More...
 
bool Wait (const std::chrono::nanoseconds duration)
 Waits for the specified number of nanoseconds. More...
 
bool WasStarted (void) const
 Alias of the IsInitiated method More...
 

Static Public Member Functions

static std::shared_ptr< CoreContextCurrentContext (void)
 Identical to CurrentContextOrNull, except returns the global context instead of a null pointer More...
 
static const std::shared_ptr< CoreContext > & CurrentContextOrNull (void)
 The shared pointer to the current context. More...
 
static void EvictCurrent (void)
 Makes no context current. More...
 
static std::shared_ptr< CoreContextGetGlobal (void)
 Returns a shared reference to the global context. More...
 
template<typename T >
static void InjectCurrent (void)
 Injects a type into the current context. More...
 
static std::shared_ptr< CoreContextSetCurrent (const std::shared_ptr< CoreContext > &ctxt)
 Static version of SetCurrent, may be invoked with nullptr More...
 
static std::shared_ptr< CoreContextSetCurrent (std::shared_ptr< CoreContext > &&ctxt)
 Move-optimized version of SetCurrent More...
 

Protected Member Functions

template<class Fn >
void RegisterFactoryFn (Fn &&fn)
 Registers a factory function, a lambda which is capable of constructing decltype(fn()) More...
 

Detailed Description

A top-level container class representing an autowiring domain, a minimum broadcast domain, and a thread execution domain.

A context is the basic unit of organization within an autowired application. The scope of a context determines:

Dependencies can be injected into a context using Autowired or AutoRequired. The system looks in the current context for an existing object of the required type to satisfy the dependency. If one does not exist, it looks in parent contexts. When using AutoRequired, a new instance of the required type is created if no existing object is found. Otherwise, the dependency is satisfied when another object of the same type (or subtype) is added to the context (or one of its parents). This resolution system carries the restriction that only one instance of an Autowired type can exist in the same branch of the context tree.

In addition, an Autowired member of a context exists for as long as that context exists.

Autowired dependencies do not need to meet any special requirements such as inheriting from a particular Autowiring type or implementing a particular interface. However, if a type contains Autowired members, instances of that type must be Autowired to a context in order for the dependencies of their members to be satisfied.

Contexts can be created with AutoCreateContext and AutoCreateContextT. The global context is created automatically; get a reference to it using AutoGlobalContext.

AutoCreateContext childContext;
class Foo{}; //dummy class
AutoCreateContextT<Foo> childContextWithSigil;

Contexts can be enumerated using the ContextEnumerator class. You can restrict enumeration to those contexts marked with a given sigil with ContextEnumeratorT<Sigil>. You can also enumerate the current context with CurrentContextEnumerator.

for(auto context : ContextEnumerator(global)){
std::cout << "Enumerating "
<< autowiring::demangle(&context->GetSigilType())
<< " within global context."
<< std::endl;
}
for(auto context : ContextEnumeratorT<Foo>(childContext)){
std::cout << "Enumerating "
<< autowiring::demangle(&context->GetSigilType())
<< " within childContext."
<< std::endl;
}
for(auto context : CurrentContextEnumerator()){
std::cout << "Enumerating "
<< autowiring::demangle(&context->GetSigilType())
<< " in current context."
<< std::endl;
}

Autowired members of a context can pass information with a filter graph. You can also pass data from one context to another in the same way. A context can also snoop on another context's filter graph packets to receive data it wouldn't otherwise have access to. Use Bolt objects to receive notification when a context of a particular sigil type is created. This allows you to set up snooping whenever a particular type of context is created.

Threads and filter graphs require that the context's Initiate() function is called.

Member Function Documentation

template<typename T >
void CoreContext::Add ( const std::shared_ptr< T > &  ptr)
inline

Introduces the specified pointer to this context explicitly

Parameters
ptrThe interface to make available in this context

Add is similar in behavior to Inject, except that the passed pointer is not treated as a concrete type. This means that other interfaces implemented by ptr will not be available for autowiring unless explicitly made discoverable by another call to Add.

It is an error to add a type which is already autowirable in a context.

void CoreContext::AddSnooper ( const autowiring::CoreObjectDescriptor &  traits)

Runtime version of AddSnooper

Referenced by AddSnooper().

template<class T >
void CoreContext::AddSnooper ( const std::shared_ptr< T > &  pSnooper)
inline

Registers the specified event receiver to receive messages from this context

This enables the passed event receiver to snoop events that are broadcast from a parent context. The passed event receiver MUST exist in a parent context, or the behavior of this method may be undefined during teardown.

The snooper will not receive any events broadcast from parent contexts. ONLY events broadcast in THIS context will be forwarded to the snooper.

template<class T >
void CoreContext::AddSnooper ( const Autowired< T > &  snooper)
inline

Resolution overload

template<typename T >
const std::shared_ptr<T>& CoreContext::Await ( void  )
inline

Similar to Inject, except will block until the specified type is available in the context

Returns
An instance of type T

This method will throw an exception if the context is terminated when the call is made or while waiting for injection to take place.

Referenced by Await().

template<typename T >
std::shared_ptr<T> CoreContext::Await ( std::chrono::nanoseconds  timeout)
inline

Timed version of Await

Returns
An instance of type T, or nullptr if the timeout has been reached
const AnySharedPointer& CoreContext::Await ( auto_id  id)

Runtime Await variant

AnySharedPointer CoreContext::Await ( auto_id  id,
std::chrono::nanoseconds  timeout 
)

Runtime Await variant

template<class T , class... Sigils>
void CoreContext::BoltTo ( void  )
inline

Injects the specified type T into all subcontexts created with one of the matching sigil types.

std::vector<const autowiring::CoreObjectDescriptor*> CoreContext::BuildObjectState ( void  ) const

Gets a snapshot of all of the objects currently in the context

The returned vector will only be valid for as long as this CoreContext is

std::vector<std::shared_ptr<BasicThread> > CoreContext::CopyBasicThreadList ( void  ) const

A copy of the current list of child CoreRunnables of this context.

No guarantee is made about how long the returned collection will be consistent within this context. A thread may potentially be added to the context after the method returns.

template<class T >
std::shared_ptr<CoreContextT<T> > CoreContext::Create ( void  )
inline

Creates a child context of this context.

Using using AutoCreateContext or AutoCreateContextT is the prefered way to create children of the current context.

AutoCreateContextT<MySigil&rt; myMarkedContext;
static std::shared_ptr<CoreContext> CoreContext::CurrentContext ( void  )
static

Identical to CurrentContextOrNull, except returns the global context instead of a null pointer

Referenced by InjectCurrent().

static const std::shared_ptr<CoreContext>& CoreContext::CurrentContextOrNull ( void  )
static

The shared pointer to the current context.

Returns
A shared pointer to the current CoreContext instance of the current thread, or else nullptr, if no context is current.

This works by using thread-local store, and so is safe in multithreaded systems. The current context is assigned before invoking a CoreRunnable instance's Run method, and it's also assigned when a context is first constructed by a thread.

bool CoreContext::DelayUntilInitiated ( void  )

Waits until the context is initiated or, if never initiated, until it starts shutting down.

Returns
True if initiated, false if shutting down.
void CoreContext::Dump ( std::ostream &  os) const

Utility debug method for writing a snapshot of this context to the specified output stream

template<class T >
void CoreContext::Enable ( void  )
inline

Allows a specifically named class to be "bolted" to this context or one of its subcontexts.

Call Enable<T> before calling BoltTo<T>. If the specified type does not inherit from Bolt, this method has no effect.

static void CoreContext::EvictCurrent ( void  )
static

Makes no context current.

Generally speaking, if you just want to release a reference to the current context, simply make the global context current instead.

This method is identical to CoreContext::SetCurrent(nullptr)

void CoreContext::FilterException ( void  )

Filters std::current_exception using any registered exception filters, or rethrows.

The passed exception is assumed to be a generic exception whose default behavior shall be to tear down the context. It will be the caller's responsibility to ensure that this behavior is observed.

If the exception is successfully handled by a filter, this method returns cleanly. Otherwise, this method is equivalent to std::rethrow_exception.

void CoreContext::FilterFiringException ( const JunctionBoxBase *  pProxy,
CoreObject *  pRecipient 
)

Filters a std::current_exception thrown by an EventSenderBase during a Fire

Parameters
pProxyThe sender of the event
pRecipientThe recipient of the event
std::shared_ptr<CoreContext> CoreContext::FirstChild ( void  ) const

The first child in the set of this context's children.

auto_id CoreContext::GetAutoTypeId ( const AnySharedPointer &  ptr) const

Gets the type information for the instance referenced by the specified shared pointer.

The returned type structure will be the actual type of the specified object as defined at the time of injection. In the case of a static factory new or AutoFactory new, this type will be the type of the interface. All other members are the concrete type actually injected, as opposed to the type unifier for that type.

This method will throw an exception if the passed shared pointer is not strictly a member of this context.

Returns
The type identifier of the referenced instance.
static std::shared_ptr<CoreContext> CoreContext::GetGlobal ( void  )
static

Returns a shared reference to the global context.

See also
AutoGlobalContext, GlobalCoreContext
std::vector<CoreRunnable*> CoreContext::GetRunnables ( void  ) const

Returns a copy of the list of runnables

This list is intended primarily for diagnostic purposes. The pointers are dumb pointers, and may be invalidated if the caller is not careful to hold a shared pointer to the context.

template<class T >
bool CoreContext::Has ( void  ) const
inline

True, if an instance of the specified type exists and dependencies of that type can be autowired in this context.

void CoreContext::Initiate ( void  )

Starts all registered threads and enables events and the flow of filter graph packets.

template<typename T , typename... Args>
std::shared_ptr<T> CoreContext::Inject ( Args &&...  args)
inline

Injects the specified types into this context.

Arguments will be passed to the T constructor, if provided.

template<typename T >
static void CoreContext::InjectCurrent ( void  )
inlinestatic

Injects a type into the current context.

bool CoreContext::IsAncestorOf ( const CoreContext child) const
inline

Reports whether the specified context is an ancestor of this context.

This method will also return true if this == child.

Returns
True if this context is an ancestor of the specified context.
bool CoreContext::IsInitiated ( void  ) const
inline

True, if the context has been initiated.

This method will return true even if the context is currently shut down. Once the context is shut down, the return value of this method is guaranteed to not change.

Referenced by WasStarted().

bool CoreContext::IsQuiescent ( void  ) const

Retrieves the system's current quiescence status

bool CoreContext::IsRunning ( void  ) const
inline

True, if the context is presently running.

This method may return false even if IsInitiated returns true if the parent context has not yet been initiated.

bool CoreContext::IsShutdown ( void  ) const
inline
Returns
True if CoreRunnable instances in this context should begin teardown operations
std::shared_ptr<CoreContext> CoreContext::NextSibling ( void  ) const

The next context sharing the same parent, or null if this is the last entry in the list

template<class T , class Fn >
void CoreContext::NotifyWhenAutowired ( Fn &&  listener)
inline

Adds a post-attachment listener in this context for a particular autowired member. There is no guarantee for the context in which the listener will be called.

This method will succeed if slot was constructed in this context or any parent context. If the passed slot was not created in this context or a parent context, an exception will be thrown.

It's possible that the passed slot will never be filled, and instead the corresponding instance destroyed without ever having been initialized.

If the passed slot is already autowired, then the listener will be invoked immediately from the body of this method. Care should be taken to avoid deadlocks in this case–either the caller must not be holding any locks when this method is invoked, or the caller should design the listener method such that it may be substitutde in place for the notification routine.

void CoreContext::Quiescent ( void  ) const

Identical to Wait, except blocks only until the threads in this and all descendant contexts have stopped

This method intrinsically may imply a race condition unless the caller is careful to ensure it retains total control over injection and subcontext creation events. In a single-threaded system, the currrent context and all child contexts are guaranteed to have no CoreRunnable instances in a running state.

bool CoreContext::Quiescent ( std::chrono::nanoseconds  duration) const

Timed version of Quiescent

template<class Fn >
void CoreContext::RegisterFactoryFn ( Fn &&  fn)
inlineprotected

Registers a factory function, a lambda which is capable of constructing decltype(fn())

void CoreContext::RemoveSnooper ( const autowiring::CoreObjectDescriptor &  traits)

Runtime version of RemoveSnooper

template<class T >
void CoreContext::RemoveSnooper ( const std::shared_ptr< T > &  pSnooper)
inline

Unregisters a snooper previously registered to receive snooped events

It is an error to call this method without a prior call to AddSnooper

template<class T >
void CoreContext::RemoveSnooper ( const Autowired< T > &  snooper)
inline

Resolution overload of RemoveSnooper

static std::shared_ptr<CoreContext> CoreContext::SetCurrent ( const std::shared_ptr< CoreContext > &  ctxt)
static

Static version of SetCurrent, may be invoked with nullptr

static std::shared_ptr<CoreContext> CoreContext::SetCurrent ( std::shared_ptr< CoreContext > &&  ctxt)
static

Move-optimized version of SetCurrent

std::shared_ptr<CoreContext> CoreContext::SetCurrent ( void  )

Makes this context the current context.

Returns
The previously current context, or else nullptr if no context was current.
void CoreContext::SetUnlinkOnTeardown ( bool  unlinkOnTeardown)
inline

Sets the context's teardown unlink behavior

If this feature is turned on, then during context destruction and after teardown listeners have been run, all context members will be scanned for uses of Autowired. If a context member has such a field, and that field points to another member of the current context, then the field will be unlinked.

If a field is AutoRequired, it is skipped. If the autowiring was satisfied outside of the context (for instance, at global scope), it's also skipped. AutowiredFast uses aren't registered anywhere, so they are also skipped.

This method may be called at any time where a valid CoreContext reference exists. CoreContext does not track additional state if this flag is set.

Teardown unlinking is the default behavior. </reamrks>

void CoreContext::SignalShutdown ( bool  wait = false,
ShutdownMode  shutdownMode = ShutdownMode::Graceful 
)

Begins shutdown of this context, optionally waiting for child contexts and threads to also shut down before returning.

Parameters
waitSpecifies whether the function should wait for all child contexts to exit before returning
shutdownModeSpecifies whether CoreThread objects should run all pending jobs or should shutdown immediately.

After this method is invoked, no new events can be dispatched within this context or any descendant context, whether those events are fired in this context or one above, and regardless of whether these events are fired or deferred. Event receivers in this context will also not receive any messages.

Filter graph packets will not be sent to receivers.

The OnStop() method of all threads in the context is invoked. The specified shutdown mode determines whether the graceful parameter of OnStop() is set to true or false.

Referenced by Inject(), and SignalTerminate().

void CoreContext::SignalTerminate ( bool  wait = true)
inline

Shuts down the context with the Immediate shutdown mode.

The same as calling SignalShutdown(true, ShutdownMode::Immediate).

void CoreContext::Wait ( void  )

Waits until the context begins shutting down (IsShutdown is true) and all threads and child threads have terminated.

You can use this function to keep a context in scope while it processes events, etc. For example, to prevent exiting from the program's main() function:

int main(){
// set up and initiate context...
ctxt->Wait();
}
bool CoreContext::Wait ( const std::chrono::nanoseconds  duration)

Waits for the specified number of nanoseconds.

bool CoreContext::WasStarted ( void  ) const
inline

Alias of the IsInitiated method


The documentation for this class was generated from the following file: