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