question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

About factory provider design, why can not direct set as singleton.

See original GitHub issue
class FooList {
  public void add(str: string) {}
}
di.register<FooList>(
  FooList, 
  {
    useFactory: (d) => {
      const obj = new FooList();
      obj.add('foo1');
      return obj;
    }
  },
 {singleton: true}
); 

const result1 = di.resolve<FooList>(FooList);
const result2 = di.resolve<FooList>(FooList);

console.log(result1 === result2); 

Expected Behavior

Console result: true

Current Behavior

Throw: Cannot use {singleton: true} with ValueProviders or FactoryProviders

Solution

Use TokenProvider again.

di.register<FooList>(
  'FooListFactory', 
  {
    useFactory: (d) => {
      const obj = new FooList();
      obj.add('foo1');
      return obj;
    }
  }
);
di.register<FooList>(
  FooList, 
  {useToken:  'FooListFactory',},
  {singleton: true}
);

But, why can not direct set it.

Is it a bug ? Or some problem of design?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
spikyjtcommented, Jul 29, 2020

I appreciate this is old, but who says we want to use a factory to instantiate an instance each time we resolve a token? What if we want a singleton which requires some specific set up (i.e. not just mapped to any old instance of a class) but we don’t want to do that set up at registration, preferring to delay it until first resolution? This could be particularly useful if the set up is heavy and we either don’t want it to happen at the start or even at all if unused. Perhaps there is another way to achieve this?

1reaction
miklcommented, Oct 10, 2020

Ditto here, I’ve been using useFactory to construct non-class things, like this:

function loggerFactory(conf: Configuration) {

  return createLogger({
    level: conf.get<string>('logLevel')
  })
}

container.register<Logger>(LOGGER, {
  useFactory: (dc) => loggerFactory(dc.resolve(Configuration))
})

Having to wrap that in instanceCachingFactory does work:

container.register<Logger>(LOGGER, {
  useFactory: instanceCachingFactory<Logger>((dc) =>
    loggerFactory(dc.resolve(Configuration))
  )
})

…but it would be better ergonomics if there was an option for this.

Read more comments on GitHub >

github_iconTop Results From Across the Web

About factory provider design, why can not direct set ... - GitHub
This is by design, singleton/transient doesn't really make much sense for a factory. Since with a factory, we want the factory method to...
Read more >
Difference between singleton and factory pattern
A singleton pattern ensures that you always get back the same instance of whatever type you are retrieving, whereas the factory pattern ...
Read more >
Dependency injection guidelines - .NET | Microsoft Learn
Avoid stateful, static classes and members. Avoid creating global state by designing apps to use singleton services instead. Avoid direct ...
Read more >
Java Singleton Design Pattern Best Practices with Examples
If your singleton class is not using a lot of resources, this is the approach to use. But in most of the scenarios,...
Read more >
Introduction to Creational Design Patterns - Baeldung
An introduction to four fundamental creational design patterns: Singleton, Factory Method, Abstract Factory, and Builder.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found