In Unity, as I know I can use the following 2 options to register a singleton instance:
IConfiguration globalConfig = new Configuration();
container.RegisterInstance<IConfiguration>(globalConfig);
container.RegisterType<IConfiguration, Configuration>(new ContainerControlledLifetimeManager());
Is there any difference between these 2 ways? What is the preferred way to register a singleton instance?
Instances can be registered as global singletons by using Singleton lifetime manager: container. RegisterInstance("Some Name", instance, InstanceLifetime. Singleton); container.
Instance is a way of achieving access without instantiation in Unity, since we're forced to inherit from MonoBehaviour, which - like you said - is not the definition of Singleton, but something we need to do in order to have purposefulfilling Singleton behaviour without adding dependency injection where you register ...
The first way registers an instance. You have to create the instance of the object when you do it.
The second way is not a singleton. It's a "singleton for any resolution by the container or any of it's child containers". The first time it would ever be resolve would "fix the state" of the object and register for any further resolutions, within the LifetimeManager
.
For example, let's say you have the following class:
class AA
{
public Datetime When { get; set; }
public AA()
{
this.When = Datetime.Now;
}
}
In the first case, When
would be before the registration, in the second case it would be whenever you actually resolve for that type/interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With