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 to http://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?
P.S. If an example helps, serviceProvider provides access to a logging object. I want almost every class to log. I don't want to pass a reference to the logging object to every class.
That's not quite what the warning in the documentation is getting at. The IServiceProvider isn't a global variable in this context; it's a method parameter, and so each invocation of Execute gets its own provider.
For improved performance, Microsoft Dynamics CRM caches plug-in instances. The plug-in's Execute method should be written to be stateless because the constructor is not called for every invocation of the plug-in. In addition, multiple threads could be running the plug-in at the same time. All per invocation state information is stored in the context. This means that you should not use global class variables in plug-ins [Emphasis mine].
There's nothing wrong with passing objects from the context to helper classes which need them. The warning advises against storing something in a field ("class variable") on the plugin class itself, which may affect a subsequent call to Execute on the same instance, or cause concurrency problems if Execute is called by multiple threads on the same instance simultaneously.
Of course, this "globalness" has to be considered transitively. If you store anything in either the plugin class or in a helper class in any way that multiple calls to Execute can access (using fields on the plugin class or statics on either plugin or helper classes, for example), you leave yourself open to the same problem.
As a separate consideration, I would write the helper classes involved to accept types as specific to their function as possible - down to the level of individual entities - rather than the entire IServiceProvider. It's much easier to test a class which needs only an EntityReference than one which needs to have an entire IServiceProvider and IPluginExecutionContext mocked up.
On global variables vs injecting values required by classes
You're right, this is something that comes up everywhere in object-oriented code. Take a look at these two implementations:
public class CustomEntityFrubber
{
public CustomEntityFrubber(IOrganizationService service, Guid entityIdToFrub)
{
this.service = service;
this.entityId = entityIdToFrub;
}
public void FrubTheEntity()
{
// Do something with service and entityId.
}
private readonly IOrganizationService service;
private readonly Guid entityId;
}
// Initialised by the plugin's Execute method.
public static class GlobalPluginParameters
{
public static IOrganizationService Service
{
get { return service; }
set { service = value; }
}
public static Guid EntityIdToFrub
{
get { return entityId; }
set { entityId = value; }
}
[ThreadStatic]
private static IOrganizationService service;
[ThreadStatic]
private static Guid entityId;
}
public class CustomEntityFrubber
{
public FrubTheEntity()
{
// Do something with the members on GlobalPluginParameters.
}
}
So assume you've implemented something like the second approach, and now you have a bunch of classes using GlobalPluginParameters. Everything is going fine until you discover that one of them is occasionally failing because it needs an instance of IOrganizationService obtained by calling CreateOrganizationService(null), so it accesses CRM as the system user rather than the calling user (who doesn't always have the required privileges).
Fixing the second approach requires you to add another field to your growing list of global variables, remembering to make it ThreadStatic to avoid concurrency problems, then changing the code of CustomEntityFrubber to use the new SystemService property. You have tight coupling between all these classes.
Not only that, all these global variables hang around between plugin invocations. If your code has a bug that somehow bypasses the assignment of GlobalPluginParameters.EntityIdToFrub, suddenly your plugin is inexplicably operating on data that wasn't passed to it by the current call to Execute.
It's also not obvious exactly which of these global variables the CustomEntityFrubber requires, unless you read its code. Multiply that by however many helper classes you have, and maintaining this code starts to become a headache. "Now, does this object need me to have set Guid1 or Guid2 before I call it?" On top of that, the class itself can't be sure that some other code won't go and change the values of global variables it was relying on.
If you used the first approach, you simply pass in a different value to the CustomEntityFrubber constructor, with no further code changes needed. Furthermore, there's no stale data hanging around. The constructor makes it obvious which dependencies the class has, and once it has them, it can be sure that they don't change except in ways they were designed for.
As you say, you shouldn't put a member variable on the plugin since instances are cached and reused between requests by the plugin pipeline.
The approach I take is to create a class that perform the task you need and pass a modified LocalPluginContext (making it a public class) provided by the Developer Toolkit (http://msdn.microsoft.com/en-us/library/hh372957.aspx) on the constructor. Your class then can store the instance for the purposes of executing it's work just in the same way you would with any other piece of code. You are essentially de-coupling from the restrictions imposed by the Plugin framework. This approach also makes it easier to unit test since you only need to provide the execution context to your class rather than mocking the entire plugin pipeline.
It's worth noting that there is a bug in the automatically generated Plugin.cs class in the Developer Toolkit where it doesn't set the ServiceProvider property - At the end of the constructor of the LocalPluginContext add the line:
this.ServiceProvider = serviceProvider;
I have seen some implementations of an IoC approach in Plugins - but IMHO it makes the plugin code way too complex. I'd recommend making your plugins lean and simple to avoid threading/performance issues.
There are multiple things I would worry about in this design request (not that it's bad, just that one should be aware of, and anticipate).
IOrganizationService is not multi-thread safe. I'm assuming that other aspects of the IServiceProvider are not as well.
Testing things at an IServiceProvider level is much more complicated due to the additional properties that have to be mocked
You'd need a method for handle logging if you ever decided to call logic that is currently in your plugin, outside of the plugin (e.g. a command line service).
If you don't want to be passing the object around everywhere, the simple solution is to create a static property on some class that you can set it upon plugin execution, and then access from anywhere.
Of course now you have to handle issue #1 from above, so it'd have to be a singleton manager of some sort, that would probably use the current thread's id to set and retrieve the value for that thread. That way if the plugin is fired twice, you could retrieve the correct context based on your currently executing thread. (Edit Rather than some funky thread id lookup dictionary, #shambulator's ThreadStatic property should work)
For issue #2, I wouldn't be storing the IServiceProvider as is, but split up it's different properties (e.g. IPluginExecutionContext, IOrganizationService, etc)
For issue #3, it might make sense to store an action or a function in your manager rather than the object values themselves. For example, if rather than storing the IPluginExecutionContext, store a func that accepts a string to log and uses the IPlurginExeuctionContext to log. This allows other code to setup it's own logging, without being dependent on executing from within a plugin.
I haven't made any of these plugins myself, but I would treat the IServiceProvider like an I/O device.
Get the data you need from it and convert that data to format that suits your plugin. Use the transformed data to set up the other classes. Get the the output from the other classes and then translate back to terms the IServiceProvider can understand and use.
Your input and output are dependent on the IServiceProvider, but the processing doesn't have to be.
From Eduardo Avaria at http://social.microsoft.com/Forums/en-US/f433fafa-aff7-493d-8ff7-5868c09a9a9b/how-to-avoid-passing-a-context-reference-among-classes
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.
Related
If I have a method outside it's callers scope that does a few things, and I have to call this method multiple times in multiple places. Is there any way to make the entire scope of the caller available to the method without passing parameters and also without using global variables? Like if I need it to have an access to a List, an entity framework context
Instead of
myMethod(string _string, List<string> _stringList, EntityContext _db)
{
//log _string to a database table
//add _string to _stringList
//etc.
}
Is there a way I can just pass the _string and make the method inherit the scope as if I'm just writing the same three lines of code everywhere I call this method? It seems a lot cleaner to call myMethod("foo") than myMethod("foo", stringList, MyEntities).
I could create a class, instantiate it, and call the class, but I'm just plain curious if scope inheritance or scope passing is a thing.
Absolutely don't do that. If you have a context you need to pass, use a class to represent the context needed, but don't try to handwave it away and hide it. It makes for unmaintainable code full of interdependencies.
In fact, the "bother" or "overhead" of passing the context object around is a good thing: it points out that having dependencies between the elements of your software project is not free. If you think that writing out the extra parameter is "too much work", then you're missing the forest for the trees: the dependency thus introduced has a much higher mental overhead than the mere mechanics of typing an extra parameter. After you pass that context a few times, typing it will be second nature and have 0 real overhead. The typing is cheap and doesn't require thinking, but keeping in mind the dependency and how it figures in the design of the overall system is anything but.
So: if you are trying to argue that introducing the dependency is worth it, then you have to back it up with actions and actually pass the context object around. The real cost is in the dependency, not the typing. Otherwise, it's a case of "talk is cheap" :)
One way of decreasing the apparent "cost" of passing such context objects is to upset the balance and make the context object actually do something, besides just carrying data. You would then use the context object to manipulate the objects for you, instead of calling the methods on the objects. This sort of "inversion" is quite handy, and often results in better design. After all, the presence of the context indicates that there's an overarching common state, and that perhaps too much functionality is delegated to the "end object", making it intertwined with the common state, whereas it may make more sense in the context object, making the end object less dependent on the presence of any particular external state.
You'd want the context to have methods that require "seeing the big picture", i.e. being aware of the presence of multiple objects, whereas the "leaf objects" (the ones with myMethod) should have methods that don't require the context, or that are general enough not to force any particular context class.
In your case, myMethod perhaps instead of working directly on an EntityContext could generate a functor or a similar action-wrapping object that performs the action, and this could then be applied by the caller (e.g. the context) to execute the database action. This way later it'll be easier to centrally manage the queue of database operations, etc.
When I refactor large projects, this sort of a "context inversion" comes in handy often, and the need for such patterns is very common. Usually, as large projects grow, the "leaf classes" start up lean, and end up acquiring functionality that belongs at a higher level. This is why using good tooling to explore the history of the repository is an imperative, and it's equally important that the entire repository history is available, i.e. that it was properly imported to git. I personally use DeepGit to trace the history of the code I work on, and find such tool indispensable. DeepGit is free as in beer for any use, and if you're not using a tool with similar functionality, you're seriously missing out, I think.
The need to pass contexts around is usually the indicator that a higher level has to be designed and introduced, and the "leafs" then need to be slimmed down, their context-using functionality moved out into the higher level. A few years down the road yet another higher level ends up being needed, although there are projects so far gone that when you just refactor them to make sense of the code base, two or three additional layers make themselves apparent!
I know of 2 ways that can be done. Consider you have the following method:
static void myMethod(string _stringA, string _stringB, string _stringC)
{
Console.WriteLine($"{_stringA},{_stringB},{_stringC}");
}
Create an overload method in the class. For example you could create an overloaded method like:
static void myMethod(string _stringA)
{
myMethod(_stringA, "stringB", "stringC");
}
The second way (which I would not advice it) is doing it the functional way like Javascript does (by using delegates):
public delegate void MethodDelegate(string _string);
static MethodDelegate mMethod1;
static MethodDelegate mMethod2;
static void Main(string[] args)
{
mMethod1 = delegate (string s) { myMethod(s, "method1-str-a", "method1-str-b"); };
mMethod1("str1");
mMethod2 = delegate (string s) { myMethod(s, "method2-str-a", "method2-str-b"); };
mMethod2("str2");
}
I was wondering what is the best practice for accessing the owner instance when using composition (not aggregation)
public class Manager
{
public List<ElementToManage> Listelmt;
public List<Filter> ListeFilters;
public void LoadState(){}
}
public class Filter
{
public ElementToManage instance1;
public ElementToManage instance2;
public object value1;
public object value2;
public LoadState()
{
//need to access the property Listelmt in the owner instance (manager instance)
//instance1 = Listelmt.SingleOrDefault(...
}
}
So far I'm thinking about two possibilities:
Keep a reference to the owner in the Filter instance.
Declare an event in the Filter class. The manager instance subscribe to it, and the filter throw it when needed.
I feel more like using the second possibility. It seems more OOP to me, and there is less dependencies between the classes ( any refactoring later will be easier),
But debugging and tracing may be a bit harder on the long run.
Regarding business layer classes, i don't remember seeing events for this purpose.
Any insight would be greatly appreciated
There is no concept of an "owner" of a class instance, there should not be any strong coupling between the Filter instance and the object that happens to have an instance of it.
That being the case an event seems appropriate: It allows for loose coupling while enabling the functionality you want. If you went with option #1 on the other hand you would limit the overall usefulness of the Filter class - now it can only be contained in Manager classes, I don't think that is what you would want.
Overall looking at your code you might want to pass in the relevant data the method LoadState operates on so it doesn't have to "reach out".
I recomend the reference to owner of filter instance. The event can be handled by more handlers and can change result of previous handler(s). And you propadly don't want change the owner during lifetime of Filter without notification the Filter instance.
My short answer : Neither.
First option to keep a reference to the owner is problematic for several reasons. Filter class no longer has a single responsibility. Filter and Manager are tightly coupled. etc.
Second option is only a little better, and yes I've used events in similar scenearios, it rarely if ever ends well.
It's difficult to give a definite advice without more specific details. Some thoughts:
1) Are you sure your classes are as they should be? Maybe there should be a class to compose a single ElementToManage and a single Filter ?
2) Who is responsible for creating a Filter? For example, if it is Manager, maybe the Manager can give the list as a construction parameter? Maybe you can create a FilterFactory class that does any needed initializations.
3) Who calls filter.LoadState()? Maybe the needed list could be passed as a parameter to the LoadState() method.
4) I frequently use an "Initialization Design Pattern" (my terminology) For example I'll have a BinaryTree where parent and child will point to each other. The Factory constructs the nodes in a plain state, and than calls an initialize method with other needed objects. The class becomes complicated because I probably need to ensure that an uninitialized object raises an error for every other usage, and need to ensure that an object is initialized only once, is initialized only through the Factory, etc. But if it works, it is usually the best solution, in my opinion.
5) I'm still trying to learn "Dependency Injection" and getting nowhere, I guess it may have something to do with your question. I wonder if someone will come with an answer involving Dependency Injection.
When looking at the source code of a couple of projects I found a pattern I can not quite understand.
For instance in FubuMVC and Common Service Locator a Func is used when a static provider is changed.
Can anyone explain what the benefit is of using:
private static Func<IServiceLocator> currentProvider;
public static IServiceLocator Current
{
get { return currentProvider(); }
}
public static void SetLocatorProvider(Func<IServiceLocator> newProvider)
{
currentProvider = newProvider;
}
instead of:
private static IServiceLocator current;
public static IServiceLocator Current
{
get { return current; }
}
public static void SetLocator(IServiceLocator newInstance)
{
current = newInstance;
}
The major advantage of the first model over the second is what's called "lazy initialization". In the second example, as soon as SetLocator is called, you must have an IServiceLocator instance loaded in memory and ready to go. If such instances are expensive to create, and/or created along with a bunch of other objects at once (like on app startup), it's a good idea to try to delay actual creation of the object to reduce noticeable delays to the user. Also, if the dependency may not be used by the dependent class (say it's only needed for certain operations, and the class can do other things that don't require the dependency), it would be a waste to instantiate one.
The solution is to provide a "factory method" instead of an actual instance. When the instance is actually needed, the factory method is called, and the instance is created at the last possible moment before it's used. This reduces front-end loading times and avoids creating unneeded dependencies.
Good answer by #KeithS. Another thing to note here is what happens under the covers of the initialization of certain instances. Keeping a reference to intentionally volatile objects can be tricky.
FubuMVC, for instance, spins up a nested StructureMap container per HTTP request which scopes all service location to that specific request. If you have classes running within that pipeline that have been built up, you'll want to use the contextual injection provided to you via THAT instance of IServiceLocator.
Theres a lot more flexibility to the implementer of newProvider. They can lazy load, async load (and and then if it's not loaded by the time the func is called it can have code to wait), they can allow it change based on runtime parameters etc.
A func allows several things
The locator creation can be delayed until it is needed. It is therefore lazy.
The provider object does not contain any state. It is not its responsiblity to shut down the locator does anything with it except to return the current locator when needed.
When the locator is reconfigured at run time or it decides that a different instance is needed it can control the lifetime of the locator as long as the calling code does not store a reference to locator.
Since the locator is returned by a method it has more flexibility e.g. to create a thread local locator so it can create many objects in each thread without the need to coordinate object creation in one global object which could become a bottleneck when many threads are involved.
I am sure the designers did could give you more points than I did why it can be a good idea to abstract away "simple" things like to return an instance of a service locator.
Yours,
Alois Kraus
Why use a GlobalClass? What are they for? I have inherited some code (shown below) and as far as I can see there is no reason why strUserName needs this. What is all for?
public static string strUserName
{
get { return m_globalVar; }
set { m_globalVar = value; }
}
Used later as:
GlobalClass.strUserName
Thanks
You get all the bugs of global state and none of the yucky direct variable access.
If you're going to do it, then your coder implemented it pretty well. He/She probably thought (correctly) that they would be free to swap out an implementation later.
Generally it's viewed as a bad idea since it makes it difficult to test the system as a whole the more globals you have in it.
My 2 cents.
When you want to use a static member of a type, you use it like ClassName.MemberName. If your code snippet is in the same class as the member you're referring (in this example, you're coding in a GlobalClass member, and using strUserName) you can omit the class name. Otherwise, it's required as the compiler wouldn't have any knowledge of what class you're referring to.
This is a common approach when dealing with Context in ASP.Net; however, the implementation would never use a single variable. So if this is a web app I could see this approach being used to indicate who the current user is (Although there are better ways to do this).
I use a simillar approach where I have a MembershipService.CurrentUser property which then pulls a user out from either SessionState or LogicalCallContext (if its a web or client app).
But in these cases these aren't global as they are scoped within narrow confines (Like the http session state).
One case where I have used a global like this would be if I have some data which is static and never changes, and is loaded from the DB (And there's not enough of the data to justify storing it in a cache). You could just store it in a static variable so you don;t have to go back to the DB.
One a side note why was the developer using Hungarian notation to name Properties? even when there was no intellisense and all the goodness our IDEs provide we never used hungarian notation on Properties.
#Jayne, #Josh, it's hard to tell - but the code in the question could also be a static accessor to a static field - somewhat different than #Josh's static helper example (where you use instance or context variables within your helper).
Static Helper methods are a good way to conveniently abstract stateless chunks of functionality. However in the example there is potential for the global variable to be stateful - Demeter's Law guides us that you should only play with state that you own or are given e.g. by parameters.
http://www.c2.com/cgi/wiki?LawOfDemeter
Given the rules there occasional times when it is necessary to break them. You should trade the risk of using global state (primarily the risk of creating state/concurrency bugs) vs. the necessity to use globals.
Well if you want a piece of data to be available to any other class running in the jvm then the Global Class is the way to go.
There are only two slight problems;
One. The implmentation shown is not thread safe. The set... method of any global class should be marked critical or wrapped in a mutex.
Even in the niave example above consider what happens if two threads run simultaniously:
set("Joe") and set("Frederick") could result in "Joederick" or "Fre" or some other permutation.
Two. It doesnt scale well. "Global" refers to a single jvm. A more complex runtime environment like Jboss could be runnning several inter communicating jvms. So the global userid could be 'Joe' or 'Frederick' depending on which jvm your EJB is scheduled.
I am running into a design disagreement with a co-worker and would like people's opinion on object constructor design. In brief, which object construction method would you prefer and why?
public class myClass
{
Application m_App;
public myClass(ApplicationObject app)
{
m_App = app;
}
public method DoSomething
{
m_App.Method1();
m_App.Object.Method();
}
}
Or
public class myClass
{
Object m_someObject;
Object2 m_someOtherObject;
public myClass(Object instance, Object2 instance2)
{
m_someObject = instance;
m_someOtherObject = instance2;
}
public method DoSomething
{
m_someObject.Method();
m_someOtherObject.Method();
}
}
The back story is that I ran into what appears to be a fundamentally different view on constructing objects today. Currently, objects are constructed using an Application class which contains all of the current settings for the application (Event log destination, database strings, etc...) So the constructor for every object looks like:
public Object(Application)
Many classes hold the reference to this Application class individually. Inside each class, the values of the application are referenced as needed. E.g.
Application.ConfigurationStrings.String1 or Application.ConfigSettings.EventLog.Destination
Initially I thought you could use both methods. The problem is that in the bottom of the call stack you call the parameterized constructor then, higher up the stack, when the new object expects a reference to the application object to be there, we ran into a lot of null reference errors and saw the design flaw.
My feeling on using an application object to set every class is that it breaks encapsulation of each object and allows the Application class to become a god class which holds information for everything. I run into problems when thinking of the downsides to this method.
I wanted to change the objects constructor to accept only the arguments it needs so that public object(Application) would change to public object(classmember1, classmember2 etc...). I feel currently that this makes it more testable, isolates change, and doesn't obfuscate the necessary parameters to pass.
Currently, another programmer does not see the difference and I am having trouble finding examples or good reasons to change the design, and saying it's my instinct and just goes against the OO principles I know is not a compelling argument. Am I off base in my design thoughts? Does anyone have any points to add in favor of one or the other?
Hell, why not just make one giant class called "Do" and one method on it called "It" and pass the whole universe into the It method?
Do.It(universe)
Keep things as small as possible. Discrete means easier to debug when things inevitably break.
My view is that you give the class the smallest set of "stuff" it needs for it to do its job. The "Application" method is easier upfront but as you've seen already, it will lead to maintainence issues.
I thing Steve McConnel put it very succintly. He states,
"The difference between the
'convenience' philosophy and the
'intellectual manageability'
philosophy boils down to a difference
in emphasis between writing programs
and reading them. Maximizing scope
may indeed make programs easy to
write, but a program in which any
routine can use any variable at any
time is harder to understand than a
program that uses well-factored
routines. In such a program you can't
understand only one routine; you have
to understand all the other routines
with which that routine shares global
data. Such programs are hard to read,
hard to debug, and hard to modify." [McConnell 2004]
I wouldn't go so far as to call the Application object a "god" class; it really seems like a utility class. Is there a reason it isn't a public static class (or, better yet, a set of classes) that the other classes can use at will?