Consider the following two scenarios:
//Data Contract
public class MyValue
{
}
Scenario 1: Using a static helper class.
public class Broker
{
private string[] _userRoles;
public Broker(string[] userRoles)
{
this._userRoles = userRoles;
}
public MyValue[] GetValues()
{
return BrokerHelper.GetValues(this._userRoles);
}
}
static class BrokerHelper
{
static Dictionary<string, MyValue> _values = new Dictionary<string, MyValue>();
public static MyValue[] GetValues(string[] rolesAllowed)
{
return FilterForRoles(_values, rolesAllowed);
}
}
Scenario 2: Using an instance class.
public class Broker
{
private BrokerService _service;
public Broker(params string[] userRoles)
{
this._service = new BrokerService(userRoles);
}
public MyValue[] GetValues()
{
return _service.GetValues();
}
}
class BrokerService
{
private Dictionary<string, MyValue> _values;
private string[] _userRoles;
public BrokerService(string[] userRoles)
{
this._userRoles = userRoles;
this._values = new Dictionary<string, MyValue>();
}
public MyValue[] GetValues()
{
return FilterForRoles(_values, _userRoles);
}
}
Which of the [Broker] scenarios will scale best if used in a web environment with about 100 different roles and over a thousand users.
NOTE: Feel free to sugest any alternative approach.
You can mess up threading using either static or instance classes. However, the key to getting threading right is to ensure that two threads don’t try to access the same resource at the same time.
With static classes, by definition there’s only one copy of it around that all threads need to share nicely.
With instance classes, you CAN create one instance per thread. If you ensure that each thread only accesses it’s own instance, AND that the instance properties and methods don’t in turn access other shared resources, they should be thread safe.
In your case, I don’t see anything being changed in the classes after initialization. If you ensure you initialize your static classes in a thread safe manner (seems to be the case here), the static variant should be thread safe (since read-only access to variables) and will be a bit faster because you don’t have the overhead of creating and disposing instances.