How to store a pointer to class contructor

Mike Parker aldacron at gmail.com
Thu Dec 24 11:02:11 UTC 2020


On Thursday, 24 December 2020 at 10:33:00 UTC, Dmitriy Asondo 
wrote:
> The idea is to store somewhere services (classes) first and 
> only when the app need - instantiate services for 
> app/thread/http-request (as option) and provide values to 
> constructors via DI

There's `Object.factory`, which constructs a class instance from 
a fully-qualified name:

https://dlang.org/phobos/object.html#.Object.factory

But IIRC there are issues with it in some cases and I believe 
it's supposed to be deprecated at some point.

I'd just give the classes an interface and use function pointers 
to construct them:

```
interface IService { ... }

alias ServiceMaker = IService function();

ServiceMaker[string] serviceRegistry;

class FooService : IService { ... }
IService makeFooService() { return new FooService(); }

void registerServices() {
     serviceRegistry["FooService"] = &makeFooService;
}
```



More information about the Digitalmars-d-learn mailing list