Unity uses classes that inherit from the Lifetimemanager base class to control how the reference to the object instance is stored and how the container destroys the instances, that is, unity is managing the creation and destruction of objects based on the specific lifetime manager class.
Currently there are two lifetime manager classes available for us to use directly, and of course you can implement your own Lifetime manager class.
1. ContainerControlledLifetimeManager
Unity saves a reference to an object instance. When you get an object instance for the same type or object through the Unity container, each fetch is the same instance. In other words, the object single example mode is implemented. By default, the RegisterInstance method uses the lifetime Manager.
2. Externallycontrolledlifetimemanager
Unity saves only a weak reference to an object instance. When you get an object instance for the same type or object through the Unity container, each fetch is the same instance. However, since the container does not have a strong reference to the object after it has been created, it may appear that the GC will be recycled when it is not strongly referenced elsewhere.
Let's look at an interface and a class first, and use the following
public interface IPlayer
{
void Play ();
}
public class Mp3player:iplayer
{
public void Play ()
{
Console.WriteLine ("Playing Mp3");
}
}
Next, you will introduce the Lifetime Manager scenario by specifying the appropriate lifetime manager at Registertype and RegisterInstance.
1. Registertype
When you register a mapping relationship with Registertype, if you do not specify a Lifetimemanager, the default is to use a transient lifetime Manager. That is, every time an instance of an object is fetched through the unity container, it is recreated, that is, there is no reference to that object in the Unity container.
Look at an example:
IUnityContainer container = new UnityContainer();
container.RegisterType<IPlayer, Mp3Player>();
IPlayer player1 = container.Resolve<IPlayer>();
Console.WriteLine(string.Format("Player1 HashCode: {0}",player1.GetHashCode()));
IPlayer player2 = container.Resolve<IPlayer>();
Console.WriteLine(string.Format("Player2 HashCode: {0}",player2.GetHashCode()));
Output results: