Database interaction in constructor causes stack overflow

Topics: Troubleshooting, Writing modules
Developer
Sep 4, 2011 at 9:35 PM

Hi all!

Something weird: in my class (which is implementing an interface which derives from IDependency) it seems that the constructor can't have any code that does database interaction. The following line (but this is just an example, I obviously tried it with something sane :-)) causes a stack overflow (if debugging, gets hit infinitely):

 

var z = _orchardServices.ContentManager.Get(1);

 

The exception is actually thrown from (or rather marked on by Visual Studio) on line 21 (return _constructorFinder.FindConstructors(targetType);) of Orchard\Environment\AutofacUtil\DynamicProxy2\ConstructorFinderWrapper.cs

If I try

var z = _orchardServices.WorkContext.CurrentSite.As<MyConetentPart>();

the problem is the same, but now on line 139 of Orchard\ContentManagement\DefaultContentQuery.cs The message is slightly different: "An unhandled exception of type 'System.StackOverflowException' occurred in System.Data.SqlServerCe.dll" (as with the first line of code the message referenced System.net.dll)

Is this a bug or feature? :-) Thanks in advance!

P.S.: Now if I run the first example, the exception is thrown on line 101 of Orchard\ContentManagement\DefaultContentManager.cs  and the message is "An unhandled exception of type 'System.StackOverflowException' occurred in Orchard.Framework.DLL"

Coordinator
Sep 5, 2011 at 6:14 AM

Yes, don't do database access in a constructor. :)

Developer
Sep 5, 2011 at 6:53 AM

Thanks, I was not aware of such a feature :-). Are there any practices then to achieve the same (instead of calling a loader method in every other method)?

Coordinator
Sep 5, 2011 at 7:11 AM

If you tell me what you are trying to do, I can try to help :)

Developer
Sep 5, 2011 at 7:32 AM

Thanks a lot :-). I'm trying to load module settings in the constructor. To be more specific, I'm trying to instantiate the FacebookWebContext (Facebook SDK) class with some Facebook app settings that are saved in the database.

Coordinator
Sep 5, 2011 at 7:56 AM

Doing it from the constructor would be extremely wasteful. You'll want to do that lazily, as late as possible.

Developer
Sep 6, 2011 at 9:26 PM

I can fully justify this, you are right. I have rewritten this part so now the instantiation of the object is inside a property and then cached in a field. This way the object is created only when needed. Thanks for the help!