Tuesday, January 4, 2011

Unity Study Notes (4)

In this article we are going to talk about Lifetime managers.

The method of RegisterType and RegisterInstance can have another parameter to specify the lifetime managers.

For example:

container.RegisterType< IWriteService, WriteService>("Write", new ContainerControlledLifetimeManager());

container.RegisterInstance< IWriteService>(new WriteService(), new ExternallyControlledLifetimeManager());

In this case we can specify the lifetime manager.

The lifetime manager can also be specified in configure file:

< type type="MyUnityTest.IWriteService, MyUnityTest"
mapTo="MyUnityTest.WriteService, MyUnityTest" >
< lifetime type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
< /type>

Sometimes we can use alias, the configure file can be like:

< ?xml version="1.0" encoding="utf-8" ?>
< configuration>
< configSections>
< section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
Microsoft.Practices.Unity.Configuration" />
< /configSections>
< unity>
< typeAliases>
< typeAliase alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity"/>
< /typeAliases>
< containers>
< container name="myContainer">
< types>
< type type="MyUnityPractice.IWriteService,MyUnityPractice" name="FirstWrite"
mapTo="MyUnityPractice.FirstWriteService,MyUnityPractice" >
< lifetime type="singleton" />
< /type>
< type type="MyUnityPractice.IWriteService,MyUnityPractice" name="SecondWrite"
mapTo="MyUnityPractice.SecondWriteService,MyUnityPractice" />
< type type="MyUnityPractice.PrintBaseClass,MyUnityPractice"
mapTo="MyUnityPractice.PrintService,MyUnityPractice" />
< /types>
< /container>
< /containers>
< /unity>
< /configuration>

By default, if register the type/instance doesn't specify the LifetimeManager, it is TransientLifetimeManager. Which means every time call the Resolve or ResolveAll method, it returns a new instances.

We can also specify the LifetimeManager to be:

ContainerControlledLifetimeManager - the instance will be singleton

PerResolveLifetimeManager - similar to TransientLifetimeManager

PerThreadLifetimeManager - create instance for every thread

ExternallyControlledLifetimeManager - this is similar to singleton, but the instance is weak referenced.

About what is weak referenced and strong referenced, there are links:
http://dotnetslackers.com/Community/blogs/haissam/archive/2008/01/03/weak-references-in-net-c.aspx
And this link has some good explanations:
http://www.dotnetfunda.com/articles/article983-gc-algorithm-and-story-of-weakreference-.aspx

No comments: