Step Eight: Let MFC Initialize the Class Factories for You

In earlier days, the hapless developer was forced to register all class factories manually. Now this work is done for you when you create the project in AppWizard in the InitInstance function.

BOOL CMfcviewApp::InitInstance ()
{
// Register all OLE servers (factories) as running. This enables the
// OLE libraries to create objects from other applications.
COleObjectFactory::RegisterAll ();

return TRUE;
}

Just to show you what you save, here is a peek at what the FILEVIEW sample must do in order to define the class factory object with the IClassFactory interface and implement that interface completely to create a file viewer object:

STDMETHODIMP CFVClassFactory::CreateInstance (
LPUNKNOWN pUnkOuter, REFIID riid, PPVOID ppvObj)
{
PCFileViewer pObj;
HRESULT hr;

*ppvObj = NULL;
hr = E_OUTOFMEMORY;

// Verify that a controlling unknown asks for IUnknown.
if (NULL != pUnkOuter && ! IsEqualIID (riid, IID_IUnknown))
return E_NOINTERFACE;

// MODIFY: If you use an object other than CFileViewer,
// be sure to change the name and parameters here. I do
// recommend that you continue to follow this model, however,
// and just modify CFileViewer as necessary.
pObj = new CFileViewer (pUnkOuter, g_hInst, ObjectDestroyed);

if (NULL == pObj)
return hr;

// MODIFY: Add other parameters to Init as necessary.
hr = pObj->Init ();

if (SUCCEEDED (hr))
{
// Return the requested interface.
hr = pObj->QueryInterface (riid, ppvObj);

if (SUCCEEDED (hr))
{
// Everything worked; count the object.
g_cObj++;
return NOERROR;
}
}

// Kill the object if anything failed after creation.
delete pObj;

return hr;
}

MFC 3.1 defines special entry points for in-process servers: DllGetClassObject and DllCanUnloadNow. AppWizard also provides them when you create your project.

STDAPI DllGetClassObject (REFCLSID rclsid, REFIID riid,
LPVOID *ppv)
{
return AfxDllGetClassObject (rclsid, riid, ppv);
}

STDAPI DllCanUnloadNow (void)
{
return AfxDllCanUnloadNow ();
}