A stateless method is a method that does not affect, nor depend on, the global state, or the state of its' defining object, when executed.
In your case, it must:
- not depend on the state of the plugin object when executed
- not change the state of the plugin while executing
Here's an example where a method is not stateless;
class StatefulSum
{
private int a;
private int b;
public void SetA(int value) {
a = value;
}
public void SetB(int value) {
b = value;
}
public int ComputeSum() {
return a + b;
}
}
And this is a more subtle example of a method that is not stateless:
class SubtleStatefulSum
{
private int partialSum;
// Looks like it's stateless but it's not and in a
// concurrent environment this method is a recipe for disaster
public int ComputeSum(int a, int b)
{
partialSum = 0;
partialSum = partialSum + a;
partialSum = partialSum + b;
return partialSum;
}
}
This is a basic example of a method that is stateless.
class BasicStateless
{
public int ComputeSum(int a, int b)
{
return a + b;
}
}
Of course, the parameters of the computation could be obtained at run time using a more complex mechanism such as the case of the Dynamics CRM plugin, via the IServiceProvider parameter.
You could conceivably have a stateless method like this:
class Stateless2
{
public int ComputeSum(IServiceProvider provider)
{
var numService = (INumberService)provider.GetService(typeof(INumbersService));
int a = numService.GetNumberA();
int b = numService.GetNumberB();
return a + b;
}
}
Where the IServiceProvider instance knows how to retrieve an object that implements an INumberService interface which in turn know how to retrieve the numbers A and B. This is a combination of Dependency Injection and Inversion of Control.