Microsoft

Dev4Devs - 28 November 2009

Submitted by Robert MacLean on Sat, 11/28/2009 - 07:48

Well today is the day! Dev4Dev’s is happening at Microsoft this morning and I will be speaking on 10 12 new features in the Visual Studio 2010 IDE. For anyone wanting the slide deck and demo application I used you can grab them below.

The slide deck is more than the 6 visible slides, there is in fact 19 slides which cover the various demos and have more information on them so you too can present this to family and friends :)

Using Outlook 2010 with Google Calendar

Submitted by Robert MacLean on Thu, 10/29/2009 - 14:57
Update 1 October 2010: If you want FULL sync, then Google has updated there sync tool to support Outlook 2010 - please go to the Gmail blog for more info. Comments to this post will also be disabled as there is nothing left to say.

If you are using Google Calendar and want to use it with Outlook 2010, you will find that the Google Calendar Sync tool no longer works smile_sad_48

So what can you do? Well Outlook 2010 supports the iCal format and so does Google Calendar - so you can use that to get a basic sync between the two.

To set this up go to your calendar details page in Google Calendar (Settings link at the top of the window then Calendars and finally click on the calendar name), and at the very bottom of the is two sets of icons one public & one private. Right click the iCal icon from the private and select copy URL.

image

Now in Outlook, go to your calendar and click the Open Calendar button and select From Internet, now paste the URL in the text box and click OK.

image

There you go, your Google Calendar is now in Outlook 2010.

Downside to this is you now have two calendars in Outlook to work with, but if you click that little arrow next to the calendar name image you can have them display as one and you can easy copy/paste between them.

image

VS2010/TFS2010 Information Landslide Begins

Submitted by Robert MacLean on Tue, 10/20/2009 - 09:36

image001 Yesterday (19th Oct) the information landslide for VS2010 & TFS2010 began with a number of items appearing all over:

Microsoft Newsletters for South Africa

Submitted by Robert MacLean on Fri, 01/30/2009 - 14:16

Stumbled across this when taking myself off some newsletters I don’t read any more. When you go to the profile site there is a list of all the news letters, you select which you want to join/leave. However if you change the language to English (South Africa) there are ones specifically from Microsoft South Africa (and actually Africa as a whole). Nice to see this!

image

Invite2Messenger

Submitted by Robert MacLean on Wed, 01/28/2009 - 08:25

I don’t like Facebook for lots of reasons (how hard - and against their TOC - it is to get my data out being a big one), and one thing on Facebook that I used once and hated was their chat program (I don’t like browser based chat, not just Facebook’s). Thankfully Microsoft has solved that problem for me with the site Invite2Messenger, which lets you select your friends from Facebook and send them an invite to add you to Live Messenger. It is amazingly fast as well, working out which of the 120ish friends on Facebook have messenger accounts and which don’t in about 10 seconds and letting me have separate emails sent to each type.

The only downside to it, is that it doesn’t check who is already in messenger so a lot of my contacts got a mail asking to add me, even though they are in messenger. You can un-tick those manually… but I was lazy and this should be done automatically.

The thing that made me wonder is how Microsoft got access to that information, especially since all it asked for was the email address I use to sign in to Facebook. There was no prompt for logins or validation! In my untested theory based on running it one it may be possible to put anyone’s email in and get their friend list :( This seems like a security issue on the Facebook side… or maybe evidence of how much Microsoft’s little share in it actually has bought it!

Inauguration PhotoSynth

Submitted by Robert MacLean on Thu, 01/22/2009 - 07:58

CNN has a very cool PhotoSynth from the 2 million people who attended the US inauguration (and who uploaded them to CNN). There is some really great angles available which I didn’t see from the TV broadcast and some great close up shots of Obama. This is just another great use of Silverlight. If you think how many will use this and how many watched it streamed live with Silverlight the question of Silverlights reach must really not becoming a serious discussion point when comparing with Flash.

If want to have a look at the PhotoSynth: http://www.cnn.com/SPECIALS/2009/44.president/inauguration/themoment/

image  image

Tripping over logs: A story of Unity - Part 6

Submitted by Robert MacLean on Tue, 01/06/2009 - 19:06
Intro

The final post in the series :) Get the code here, read comments on unit testing with DI, thanks, references and further reading!

This is a multi-part series as such here is the series guide in case you are looking for the rest of the series:

This is just a final post to wrap up the series, you really should use the above links to get the actual value out of it.

Download the Final Code

You will need 7-Zip to open it.

My view on Unit Testing with DI

What excited me about DI initially is that it makes testing and in particular unit testing, so much better. The problem faced with any system you want to test is that if it is tightly coupled you can’t unit test, you can only do integration testing. By following DI, you are forced into a loosely coupled architecture which means that you can very easily test your individual components.

Let me give you a real world story on this, which involved the enterprise system I mentioned in the very first post. It read from system A, did processing and wrote to system B. The fact it was tightly coupled meant that I couldn’t even fake a message into the system, I had to generate real messages in system A and watch the flow of those messages. After a long time I dropped MSMQ between system A, the processing and system B to enable me to fake messages but even then it wasn’t great as I needed to re-write so much code to talk to these new interfaces. Lastly the processing took many hours to run to completion so proper end to end testing took days, and if a crash occurred certain processes needed to be started from scratch again.

If I had used DI for the system the first thing I could’ve done is written up two mock interfaces and swopped with real ones out using the config. This would mean I could simulate messages simply. System B was in fact MSCRM which I couldn’t run on my machine (laptop running Windows XP at the time) so being able to mock the interface to it could’ve meant that I could’ve worked on the processing engine without MSCRM being needed (i.e. a VM or server).

Next the tightly coupling of methods meant that the process had to run it’s time, but if I had implemented DI I would have each of the individual components of the processing separated out and would be able to have tested them individually. Yes, end to end processing would still be needed but I could’ve saved days of testing with this.

I haven’t actually done enough to write a post on this specific topic, so maybe once I have done more I will be more sure or maybe I will just tell you I was wrong.

Thanks, References and Further Reading

First off thanks to you, the reader, for spending time on this series and I hope you drop me a mail/@rmaclean/comment if this has helped you or you have any questions.

That said I could not have done with without a great posts I found on this subject - so here is my references:

Note that Unity is an implementation of this, there is a lot of them out there. Scott Hanselman has a list at  http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx

Lastly I could not end this series without a link to the definitive theory on DI, by Martin “wolfman” Fowler - Inversion of Control Containers and the Dependency Injection pattern. This is a must read for everyone.

The other must read is Jacob Proffitt (http://theruntime.com/blogs/jacob/Default.aspx) who is a .NET expert/guru etc… but is not a fan of DI. The reality check you will get from him should help balance the DI fan-boy crowds out.

Tripping over logs: A story of Unity - Part 5

Submitted by Robert MacLean on Tue, 01/06/2009 - 19:02
Recap + Intro

In part 1 we looked at the problem with just adding logging code and how it quickly gets messy and we looked at how the more loosely coupled the code is, the easier it is to effect changes painlessly. Then in part 2 we took that code and added Unity which gave us control via a config file as to what class our logging should use. Then in part 3 we saw some benefits of dealing with this overhead. Previously we actually got our logging nicely sorted but there was a few extra details worth mentioning, so here goes.

Note you can get Unity with the Enterprise Library from p&p group.

As I said in part 1

what I am going to do is look at a practical approach to using Unity, I will not be going into DI or IoC those topics as people smarter than me have done a much better job. If you want the theory look somewhere else, if you want to get running with Unity this is for you.

This is a multi-part series as such here is the series guide in case you are looking for the rest of the series:

Circular References

DI is actually a minefield since you can cause a circular reference easily, but injection makes that even easier to shoot yourself in the foot. What is a circular reference? The documentation (shockingly) describes it well:

  • Objects generated through constructor injection that reference each other in their constructor parameters
  • Objects generated through constructor injection where an instance of a class is passed as a parameter to its own constructor
  • Objects generated through method call injection that reference each other
  • Objects generated through property (setter) injection that reference each other

For example, the following code shows two classes that reference each other in their constructors.

public class Class1
{
  public Class1(Class2 test2)
  { ... }
}
 
public class Class2
{
  public Class2(Class1 test1)
  { ... }
}

It is the responsibility of the developer to prevent this type of error by ensuring that the members of classes they use with dependency injection do not contain circular references.

I have bolded that last line to get the point across. You have been warned!

Reflection

It’s not just interception that uses reflection, other parts do as well so make sure you understand the security implications of this: http://msdn.microsoft.com/en-us/library/9syytdak.aspx

Interceptors

I used the transparent proxy interceptor in my previous post, but there are two others. Each has pro’s and con’s, which the documentation puts in a simple table for you:

Type

Description

Use

TransparentProxyInterceptor

An instance interceptor. The proxy is created by using the .NET TransparentProxy/RealProxy infrastructure.

When the type to intercept is a MarshalByRefObject or when only methods from the type's implemented interfaces need to be intercepted.

InterfaceInterceptor

An instance interceptor. It can proxy only one interface on the object. It uses dynamic code generation to create the proxy class.

When resolving an interface mapped to a type.

VirtualMethodInterceptor

A type interceptor. It uses dynamic code generation to create a derived class that gets instantiated instead of the original, intercepted class and to hook up the call handlers.

When only virtual methods need to be intercepted.

Selection of a specific interceptor depends on your specific needs, because each one has various tradeoffs. The following table summarizes the three interceptors and their advantages and disadvantages.

Type

Advantages

Disadvantages

TransparentProxyInterceptor

Can intercept all methods of the target object (virtual, non-virtual, or interface).

The object must either implement an interface or inherit from System.MarshalByRefObject. If the marshal by reference object is not a base class, you can only proxy interface methods. The TransparentProxy process is much slower than a regular method call.

InterfaceInterceptor

Proxy supports casting to all the interfaces or types of the target object.

It only intercepts methods on a single interface. It cannot cast a proxy back to target object's class or to other interfaces on the target object.

VirtualMethodInterceptor

Calls are much faster than the TransparentProxyInterceptor.

Interception only happens on virtual methods. You must set up interception at object creation time and cannot intercept an existing object.

Rules

There is an entire rules framework available in interception which lets you enable/disable the interception based on rules. The idea is that you annotate all methods and then use the rules to filter which of those to actually run. This can, as with everything in Unity, be configured in code or in the configuration file. Here are a list of the rules (I am sure you can begin to guess what they do by their names):

  • The Assembly Matching Rule
  • The Custom Attribute Matching Rule
  • The Member Name Matching Rule
  • The Method Signature Matching Rule
  • The Namespace Matching Rule
  • The Parameter Type Matching Rule
  • The Property Matching Rule
  • The Return Type Matching Rule
  • The Tag Attribute Matching Rule
  • The Type Matching Rule

And as always you can custom develop your own rules too.

Tripping over logs: A story of Unity - Part 4

Submitted by Robert MacLean on Tue, 01/06/2009 - 18:59
Recap + Intro

In part 1 we looked at the problem with just adding logging code and how it quickly gets messy and we looked at how the more loosely coupled the code is, the easier it is to effect changes painlessly. Then in part 2 we took that code and added Unity which gave us control via a config file as to what class our logging should use. Then in part 3 we saw some benefits of dealing with this overhead, but now dear reader we get into the real issue I wanted to solve, having logging be more elegantly applied.

Note you can get Unity with the Enterprise Library from p&p group.

As I said in part 1

what I am going to do is look at a practical approach to using Unity, I will not be going into DI or IoC those topics as people smarter than me have done a much better job. If you want the theory look somewhere else, if you want to get running with Unity this is for you.

This is a multi-part series as such here is the series guide in case you are looking for the rest of the series:

Works better than Vader’s interceptor

(Once again I shine my knowledge of Star Wars in a title… which maybe is why my friends and family think of me as a geek and I see myself as cool… anyway it’s not important to the post.)

The Mary Poppins bag like magic that is happening with Unity is NOT just limited to controlling the lifetime of objects, it is actually controlling the objects. There is an invisible layer there and this allows us to do something very smart called Interception. In this scenario we intercept calls to classes or methods and apply some other code to them! Important to note is that we can only do that to objects that Unity works with so for our example, we can’t do it to the main method or the DoSomething method directly. We can refactor DoSomething into it’s own interface and class and have Unity own it as below. The key changes from our previous code are:

  • I create a instance of IWorker and do the DoSomething method of it, passing it the logger - lines 14 and 15
  • I have a new interface called IWorker and a new class based on it, called Worker - Lines 43 to 55
  • I have removed our Lolzcat’s constructor in the logging (it’s not important to show that anymore)

   1: class Program
   2:     {
   3:         static IUnityContainer container = new UnityContainer();
   4:  
   5:         static void Main(string[] args)
   6:         {
   7:             UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
   8:             section.Containers.Default.Configure(container);
   9:  
  10:             ILogger logger = container.Resolve<ILogger>();
  11:  
  12:             logger.LogThis("Application started");
  13:  
  14:             IWorker worker = container.Resolve<IWorker>();
  15:             worker.DoSomething("Robert", logger);
  16:  
  17:             Console.ReadKey();
  18:             logger.LogThis("Application Completed");
  19:         }
  20:     }
  21:  
  22:     public interface ILogger
  23:     {
  24:         void LogThis(string Message);
  25:     }
  26:  
  27:     public class DebugLogger : ILogger
  28:     {
  29:         public void LogThis(string Message)
  30:         {
  31:             System.Diagnostics.Debug.WriteLine(String.Format("{0}: {1}", DateTime.Now, Message));
  32:         }
  33:     }
  34:  
  35:     public class ConsoleLogger : ILogger
  36:     {
  37:         public void LogThis(string Message)
  38:         {
  39:             Console.WriteLine("{0}: {1}", DateTime.Now, Message);
  40:         }
  41:     }
  42:  
  43:     interface IWorker
  44:     {
  45:         void DoSomething(string Username, ILogger logger);
  46:     }
  47:  
  48:     public class Worker : IWorker
  49:     {
  50:         void IWorker.DoSomething(string Username, ILogger logger)
  51:         {
  52:             logger.LogThis("DoSomething Called with Username Parameter set to:" + Username);
  53:             Console.WriteLine("Hello {0}", Username);
  54:             logger.LogThis("DoSomething Completed");
  55:         }
  56:     }

So this runs nicely but we are still using this logger thing all the time and it isn’t much better than before.

Setup the Interception

So to fix this we will use interception and that means we need to add two more references to our solution:

image

Next we add a new using to our code:

using Microsoft.Practices.Unity.InterceptionExtension;
using System.Reflection;

Yes, that is System.Reflection there. We will use reflection to figure out values at runtime for us.

And now we will add in code to allow us to attribute our methods so that logging happens for us. For those who have no idea what I mean by attribute methods, I am talking about the Decorator Pattern, which will be familiar to those using WCF and/or LINQ at least in practice even if you didn’t know it was called that.

To do that we first need to create another new class, this time derived from HandlerAttribute and all it does is gives us the attribute to decorate the code with, lines 1 to 7 below. It returns a class of LoggingHandler (via the container) and LoggingHandler is the other new. In here we have a constructor which take an instance of ILogger (lines 13 to 16) and a Invoke method (starting on line 18). The invoke method is the brains of the operation as it is what will be run when we call our method. Note it starts with us using reflection to work out the parameters (lines 20 through 25) and then calls the logger to write the PRE method message (line 27). Next it calls getNext which gets the next handler in the stack (in our case there is none). Note you control the order of handlers via the Order parameter, line 34. After all the handlers have run their PRE methods the method actually runs, and after the getNext it starts to unwind so we can do our POST method logging, line 29.

   1: public class LoggingAttribute : HandlerAttribute
   2:     {
   3:         public override ICallHandler CreateHandler(IUnityContainer container)
   4:         {
   5:             return container.Resolve<LoggingHandler>();
   6:         }
   7:     }
   8:  
   9:     public class LoggingHandler : ICallHandler
  10:     {
  11:         ILogger _logger;
  12:  
  13:         public LoggingHandler(ILogger logger)
  14:         {
  15:             _logger = logger;
  16:         }
  17:  
  18:         public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
  19:         {
  20:             string parameters = string.Empty;
  21:             for (int counter = 0; counter < input.Inputs.Count; counter++)
  22:             {
  23:                 ParameterInfo parameterInfo = input.Inputs.GetParameterInfo(counter);
  24:                 parameters += parameterInfo.Name + " = " + input.Inputs[counter].ToString() + Environment.NewLine;
  25:             }
  26:  
  27:             _logger.LogThis(String.Format("About to call {0} with the following parameters: {1}", input.MethodBase.Name, parameters));
  28:             IMethodReturn msg = getNext()(input, getNext);
  29:             _logger.LogThis(String.Format("Call completed to {0}", input.MethodBase.Name));
  30:  
  31:             return msg;
  32:         }
  33:  
  34:         public int Order { get; set; }
  35:     }

One point I want to make here, and I think it is super cool, is note I never specify what to pass into LoggingHandler’s constructor (it needs an ILogger parameter)! Unity is smart enough to know it has an ILogger in the container and a constructor with needs one and puts them together automatically for you ;)

Right that’s a lot of code to do this, so how does it effect our other code? We’ll now our DoSomething method just looks like this below. Note the [Logging] attribute tag on line 1 which enables the logging for this method.

   1: [Logging]
   2: void IWorker.DoSomething(string Username)
   3: {
   4:     Console.WriteLine("Hello {0}", Username);
   5: }

If you think that in a massive system the fact we can just annotate methods to get functionality is great, it cleans the code up and means that developer X who is working on logging can change it WITHOUT any code changes :) Rock On!

Configuration for Interception

Our code does not run at this point :( Because we need to add some details the app.config for the system to use configuration. First we add an alias for our chosen method of interception on line 14, then we extend the unity config (similar concept to how we extended the .NET config with a config section) on lines 28 to 30, and lastly we configure the extension we added. The most important part here is how we link an interceptor to a class (lines 35 and 36). This means we can enable/disable interception via configuration.

   1: <?xml version="1.0" encoding="utf-8" ?>
   2: <configuration>
   3:     <configSections>
   4:         <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
   5:     </configSections>
   6:  
   7:     <unity>
   8:         <typeAliases>
   9:             <typeAlias alias="Logger" type="BigSystem.ConsoleLogger, BigSystem"/>
  10:             <typeAlias alias="ILogger" type="BigSystem.ILogger, BigSystem"/>
  11:             <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
  12:             <typeAlias alias="Worker" type="BigSystem.Worker, BigSystem"/>
  13:             <typeAlias alias="IWorker" type="BigSystem.IWorker, BigSystem"/>
  14:             <typeAlias alias="transparentProxy" type="Microsoft.Practices.Unity.InterceptionExtension.TransparentProxyInterceptor, Microsoft.Practices.Unity.Interception" />
  15:         </typeAliases>
  16:  
  17:         <containers>
  18:             <container>
  19:                 <types>
  20:                     <type type="ILogger" mapTo="Logger">
  21:                         <lifetime type="singleton" />
  22:                     </type>
  23:                     <type type="IWorker" mapTo="Worker">
  24:                         <lifetime type="singleton" />
  25:                     </type>
  26:                 </types>
  27:  
  28:                 <extensions>
  29:                     <add type="Microsoft.Practices.Unity.InterceptionExtension.Interception, Microsoft.Practices.Unity.Interception" />
  30:                 </extensions>
  31:  
  32:                 <extensionConfig>
  33:                     <add  name="interception" type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationElement, Microsoft.Practices.Unity.Interception.Configuration">
  34:                         <interceptors>
  35:                             <interceptor type="transparentProxy">
  36:                                 <default type="IWorker"/>
  37:                             </interceptor>
  38:                         </interceptors>
  39:                     </add>
  40:                 </extensionConfig>
  41:             </container>
  42:         </containers>
  43:     </unity>
  44: </configuration>

And that is it! It’s been a long post so I won’t go into any specific of the interception type etc… I’ll do a supplementary post on that next.

Tripping over logs: A story of Unity - Part 3

Submitted by Robert MacLean on Tue, 01/06/2009 - 18:57
Recap + Intro

In part 1 we looked at the problem with just adding logging code and how it quickly gets messy and we looked at how the more loosely coupled the code is, the easier it is to effect changes painlessly. Then in part 2 we took that code and added Unity which gave us control via a config file as to what class our logging should use. Now we are going to look at a benefit of having this Mary Poppins bag of magic controlled for us.

Note you can get Unity with the Enterprise Library from p&p group.

As I said in part 1

what I am going to do is look at a practical approach to using Unity, I will not be going into DI or IoC those topics as people smarter than me have done a much better job. If you want the theory look somewhere else, if you want to get running with Unity this is for you.

This is a multi-part series as such here is the series guide in case you are looking for the rest of the series:

The time of your life

In our code we created a global variable for the logging and just called that, but that is not always a good idea. Logging is a poor example of this, but security is a better one. If you wanted to do a security check in some methods and not others why waste time with a global variable, why not reach into the bag each time it is needed and pull one out. The problem can come in, is that performance can drop because now you are calling the constructor each time you need the object. The reality is that this issue was solved years ago in the Singleton pattern.

So can we apply that to Unity? Yes, Unity is smart enough to give us a way to do that thanks to it’s inbuilt lifetime management! To demo this I have modified the code from part 2 as follows:

  • Removed the global variable for logger and replaced it with a global variable for the container (line 3 below)
  • In DoSomething I ask for a logger at the start now (line 7 below)
  • I got a Lolzcat to add a constructor to my ConsoleLogger class to slow it down ;) Lines 45 to 49.
  • It’s not visible in the code by a new using has been added to System.Threading so that we can use the Thread.Sleep method on line 48
   1: class Program
   2:     {
   3:         static IUnityContainer container = new UnityContainer();
   4:  
   5:         static void DoSomething(string Username)
   6:         {
   7:             ILogger logger = container.Resolve<ILogger>();
   8:  
   9:             logger.LogThis("DoSomething Called with Username Parameter set to:" + Username);
  10:             Console.WriteLine("Hello {0}", Username);
  11:             logger.LogThis("DoSomething Completed");
  12:         }
  13:  
  14:         static void Main(string[] args)
  15:         {
  16:             UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
  17:             section.Containers.Default.Configure(container);
  18:  
  19:             ILogger logger = container.Resolve<ILogger>();
  20:  
  21:             logger.LogThis("Application started");
  22:  
  23:  
  24:             DoSomething("Robert");
  25:             Console.ReadKey();
  26:             logger.LogThis("Application Completed");
  27:         }
  28:     }
  29:  
  30:     public interface ILogger
  31:     {
  32:         void LogThis(string Message);
  33:     }
  34:  
  35:     public class DebugLogger : ILogger
  36:     {
  37:         public void LogThis(string Message)
  38:         {
  39:             System.Diagnostics.Debug.WriteLine(String.Format("{0}: {1}", DateTime.Now, Message));
  40:         }
  41:     }
  42:  
  43:     public class ConsoleLogger : ILogger
  44:     {
  45:         public ConsoleLogger()
  46:         {
  47:             Console.WriteLine("i iz in yourz codez, slowingz its downz");
  48:             Thread.Sleep(5000);
  49:         }
  50:  
  51:         public void LogThis(string Message)
  52:         {
  53:             Console.WriteLine("{0}: {1}", DateTime.Now, Message);
  54:         }
  55:     }

What happens if my code runs slowly now and the lolzcat message is shown twice (since I create the object twice). If I assume that it’s just an example of the overhead of the constructor (which it is), and that I need to live with it at least once then implementing the singleton pattern is the solution to this. To do it actually means two lines of changes to the app.config (one line if you want to be messy). First I add a new type alias for the ContainerControlledLifetimeManager which I have called singleton (line 11 below), and then I expand my type with a lifetime tag which links back to it (line 18 below).

   1: <?xml version="1.0" encoding="utf-8" ?>
   2: <configuration>
   3:     <configSections>
   4:         <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
   5:     </configSections>
   6:  
   7:     <unity>
   8:         <typeAliases>
   9:             <typeAlias alias="Logger" type="BigSystem.ConsoleLogger, BigSystem"/>
  10:             <typeAlias alias="ILogger" type="BigSystem.ILogger, BigSystem"/>
  11:             <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
  12:         </typeAliases>
  13:  
  14:         <containers>
  15:             <container>
  16:                 <types>
  17:                     <type type="ILogger" mapTo="Logger">
  18:                         <lifetime type="singleton" />
  19:                     </type>
  20:                 </types>
  21:             </container>
  22:         </containers>
  23:     </unity>
  24: </configuration>

Now I just rerun my application and I get the code twice as fast and one lolzcat message since the container (magic bag) has now created the object once and when I ask for it a second time it provides me the already created one! This is an amazingly useful system because it’s per mapping and out of the box are three lifetime managers and you can build your own.

For the sake of ease I will now copy and paste from the documentation on those three lifetime managers:

ContainerControlledLifetimeManager. Unity returns the same instance of the registered type or object each time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes. This lifetime manager effectively implements a singleton behavior for objects. Unity uses this lifetime manager by default for the RegisterInstance method if you do not specify a different lifetime manager. If you want singleton behavior for an object that Unity creates when you use the RegisterType method, you must explicitly specify this lifetime manager. The behavior is as follows:

  • If you used the RegisterType method to register a type, Unity creates a new instance of the registered type during the first call to the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes. Subsequent requests return the same instance.
  • If you used the RegisterInstance method to register an existing object, Unity returns this instance every time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes.

ExternallyControlledLifetimeManager. This lifetime manager allows you to register type mappings and existing objects with the container so that it maintains only a weak reference to the objects it creates when you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes based on attributes or constructor parameters within that class. Unity returns the same instance of the registered type or object each time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes. However, the container does not hold onto a strong reference to the object after it creates it, which means that the garbage collector can dispose of the object if no other code is holding a strong reference to it.

PerThreadLifetimeManager. Unity returns, on a per-thread basis, the same instance of the registered type or object each time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes. This lifetime manager effectively implements a singleton behavior for objects on a per-thread basis. PerThreadLifetimeManager returns different objects from the container for each thread. The behavior is as follows:

  • If you used the RegisterType method to register a type, Unity creates a new instance of the registered type the first time the type is resolved in a specified thread, either to answer a call to the Resolve or ResolveAll methods for the registered type or to fulfill a dependency while resolving a different type. Subsequent resolutions on the same thread return the same instance.
  • Using the RegisterInstance method to register an existing object results in the same behavior as if you just registered the lifetime container with RegisterType. Therefore, it is recommended that you do not use the RegisterInstance method to register an existing object when using the PerThreadLifetimeManager.
  • PerThreadLifetimeManager returns the object desired or permits the container to create a new instance if no such object is currently stored for the current thread. A new instance is also created if called on a different thread than the one that set the value. This lifetime manager does not dispose the instances it holds.