none
How to avoid passing a context reference among classes

    Question

  • Dynamics CRM 2011 on premise. (But this problem exists in many situations away from Dynamics CRM.)

    CRM plugins have an entry point:

    void IPlugin.Execute (IServiceProvider serviceProvider)

    (http://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.iplugin.execute.aspx)

    serviceProvider is a reference to the plugin execution context. Anything useful that a plugin does requires accessing serviceProvider, or a member of it.

    Some plugins are large and complex and contain several classes. For example, I'm working on a plugin that has a class which is instantiated multiple times. This class needs to use serviceProvider.

    One way to get access to serviceProvider from all the classes that need it would be to add a property to all those classes and then to set that property. Or to add properties for the parts of serviceProvider that each class needs. Either of these approaches would result in lots of duplicate code.

    Another approach would be to have a global variable in the scope of the thread. However, according tohttp://msdn.microsoft.com/en-us/library/cc151102.aspx one "should not use global class variables in plug-ins."

    So what is the best way to have access to serviceProvider without passing it around everywhere?

    (Please answer at http://stackoverflow.com/questions/19119714/how-to-avoid-passing-a-context-reference-among-classes)

    • Edited by cja_intgrtch Tuesday, October 01, 2013 4:06 PM I have to make URLs myself?!
    Tuesday, October 01, 2013 4:05 PM

All replies

  • Well, as someone at SO already told you, the global variables restriction is there cause the plugin won't instantiate again if it's called within the same context (the object context and probably other environmental conditions), so any custom global variable would be shared between that instances, but since the context will be the same, there's no problem in assigning it to a global variable if you want to share it between a lot of classes.

    Anyways, I'd rather pass the context on the constructors and share it have a little more control over it, but that's just me.

    Wednesday, October 02, 2013 1:09 AM
  • I added my answer over at SO :)

    Scott Durow
    Blog www.develop1.net    Follow Me
    Rockstar365
    If this post answers your question, please click "Mark As Answer" on the post and "Mark as Helpful"

    Wednesday, October 02, 2013 8:29 AM
    Answerer
  • Thank you. It's much better over there :)
    Wednesday, October 02, 2013 8:43 AM