Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Unity, what is the difference between the 2 ways to register a singleton instance?

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?

like image 981
Tony98 Avatar asked May 31 '17 18:05

Tony98


People also ask

How do I register Singleton in Unity?

Instances can be registered as global singletons by using Singleton lifetime manager: container. RegisterInstance("Some Name", instance, InstanceLifetime. Singleton); container.

What are instances Unity?

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 ...


1 Answers

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.

like image 198
Tipx Avatar answered Sep 22 '22 07:09

Tipx