Access certain objects (eg WCA) from within a content part

Topics: Writing modules
Dec 16, 2015 at 6:20 AM
Hey guys,

Pretty new Orchard site owner / developer here. Been trying to get to grips with the system for a little less than 2 weeks, and have spent some time developing basic modules and familiarising myself with certain aspects of the CMS.

I have a pretty basic question though.. I will preface this by saying that I am going to run through some of the more Orchard-fundamental type resources (eg. Orchard: Up and Running) to try and get a more holistic understanding of how everything comes together... In the mean time, I was just wondering how I can access some of the generic classes (like WorkContext, MembershipService, AuthenticationService) from within a ContentPart of a Custom Module?

I have worked with such classes while writing custom activities and have had no problem with it... Obviously, this is because custom activities can request these resources in their constructors. However, ContentParts apparently cannot have parameters in their constructors so we cannot just construct taking these classes as parameters and assign them from there.

At the moment, I simply want to create a module that will log a user in with X credentials.. Got this working perfectly fine in a custom activity but again, I had no trouble accessing authentication service etc.. If anyone has any tips I'd be most appreciative. In the mean time I'm going to go find myself some resources and get a more wholesome understanding of Orchard.
Developer
Dec 16, 2015 at 8:37 PM
Typically you would work with those services in your content part drivers, or content handlers not your content part classes themselves. There are some exceptions where you see this happening, for example to easily access some calculated data given a content part. The way that works is as follows: in your content part class, you declare and instantiate a field member of type LazyField<T>, where <T> is the type of your property. Then from your content handler, you handle the Activated<TPart> event method, from where you setup that field member by supplying a Loader and optionally a Setter. Since you're doing this from a content handler, you can use any services you need, such as WorkContext, MembershipService and AuthenticationService.

But again, depending on your exact scenario, consider working with those services from the content part driver or handler. The fact that you (think) you need them in your content part class itself is a potential smell.
Dec 17, 2015 at 10:47 PM
I meant to reply yesterday but I forgot..!

Great post. Exactly some advice I needed to hear which should help me move forward. Thanks :)