Microsoft KB Archive/152315

= PRB: When to Call AfxDaoTerm in an Automation Server =

Article ID: 152315

Article Last Modified on 11/21/2006

-

APPLIES TO

 Microsoft Foundation Class Library 4.2, when used with:  Microsoft Visual C++ 4.0 Standard Edition

 Microsoft Visual C++ 4.1 Subscription

 Microsoft Visual C++ 4.2 Enterprise Edition

 Microsoft Visual C++ 4.2 Professional Edition</li></ul>

 Microsoft Visual C++ 4.2 Enterprise Edition</li></ul>

 Microsoft Visual C++ 4.2 Professional Edition</li></ul>

 Microsoft Visual C++ 5.0 Enterprise Edition</li></ul>

 Microsoft Visual C++ 5.0 Professional Edition</li></ul> </li></ul>

-

<div class="notice_section">

This article was previously published under Q152315

<div class="symptoms_section">

SYMPTOMS
MFC DLLs and OCXs that use DAO need to call AfxDaoTerm to terminate DAO before their ExitInstance function is called. MFC, by default, calls AfxDaoTerm from within CWinApp::ExitInstance.

An automation server may expose multiple objects that use DAO. Calling AfxDaoTerm when one of these objects is destructed may have the undesired effect of terminating DAO for all other objects that may still be in use.

<div class="resolution_section">

RESOLUTION
MFC keeps an internal object lock count of automation objects in the module state. The constructor of each object exposed by the automation server calls AfxOleLockApp to increment this count and calls AfxOleUnlockApp to decrement it.

An MFC DLL automation server gets unloaded when the AfxOleCanExitApp function returns TRUE. This function checks the object lock count and returns TRUE if no objects are in use. The default implementation of DllCanUnloadNow in an AppWizard-generated automation server looks like this: STDAPI DllCanUnloadNow(void) {      AFX_MANAGE_STATE(AfxGetStaticModuleState); return AfxDllCanUnloadNow; } Add the following code to terminate DAO when no automation objects are in use any longer: STDAPI DllCanUnloadNow(void) {      AFX_MANAGE_STATE(AfxGetStaticModuleState);

if (AfxOleCanExitApp) AfxDaoTerm;

return AfxDllCanUnloadNow; }

<div class="status_section">

STATUS
This behavior is by design.

<div class="references_section">