Reputation: 1239
Suppose we want to create a collection of services, which may or may be not used by:
class ServiceCollection {
public MyService MyService = new MyService(arg1,arg2,...);
public MySecondService MySecondService = new MySecondService(arg1,arg2,...);
...
As we don't know if a service instance will be used or not - we wanted to create a service instance on-the-fly:
class ServiceCollection {
private MyService _MyService = null;
public MyService MyService {
get {
if (_MyService==null) _MyService = new MyService(arg1,arg2,...);
return _MyService;
}
}
It is a requirement in case the user code refers to a service twice - the same service instance should be used. As the code above is ... kinda long ... I wonder is the following resulution is correct or not:
class ServiceCollection {
private MyService _MyService = null;
public MyService MyService => _MyService = _MyService ?? new MyService(arg1, ...);
Or does any other (more elegant and short) solution exist for this simple problem?
Upvotes: 0
Views: 192
Reputation: 17010
I am trying to understand the architecture. In general, you can load different services, on the fly, with dependency injection. So I don't see a reason to go through the difficulty you are trying.
Or, are you trying to load balance on your side of the equation? If so, why?
There are two potential ideas here.
Architecturally, the first is great for loading dependencies via injection. The latter is better if you have the API team provide the scale for you.
Am I missing something?
Upvotes: 1