Anything related to the .NET framework
05 Feb 2009

Workflow Foundation Activity Template

WF has two two types of activities you can create, the easy one and the hard one. That’s not really their names (though it would be cool), the first (easy) is a composite activity. This is is the one that Visual Studio lets you create and is in effect just another sequential workflow which you build up and reuse.

image

However when you use them they just look like sequence activities. If you want something that looks like a “real” (read: what you get out of the box) activity to need to create the hard one which is call an activity (so clear a name, ain’t it). The smallest this can be is one class and the biggest it can be is five classes and they all basically have the same structure. So it’s weird that there is no easy way to build these, say a template. Well I have created one which sets up the base for an activity and lets you get going as quickly as possible.

Usage

To use it, select the normal Add -> New Project, and under Visual C#, My Templates will be the template called WF Activity! Some things that should become clear from that little sentence

  • You need Visual Studio 2008 (yeah, that wasn’t clear but I need to sneak it in somewhere).
  • It’s C# only
  • It creates a project for your new activity for ease of packaging purposes.
  • And for some reason if I put a space in the name, if crashes my Visual Studio - so um, that could just be me.

 

image

When you create it, it creates 4 files which all start with the name you choose (that will also be the name for your activity, so I don’t suggest putting activity in it) - For example mine was called ConsoleWriteLine so my files are:

  • ConsoleWriteLineActivity.cs
  • ConsoleWriteLineActivityDesigner.cs
  • ConsoleWriteLineActivityDesignerTheme.cs
  • ConsoleWriteLineActivityValidator.cs

image 

Special Features

I will come back to what they do but I thought I would point out that I have taken special care with the code so that if you run code analysis (fxcop) you get no issues with the code - you will get five for the project not being signed and com visibility stuff - and that StyleCop also reports no issues. I have also added in three TODO’s (if you use the VS task list)

image

  • The first one (Write Code) takes you to the Execute method in the {Project}Activity.cs file. This is what will run when your activity is executed.
  • The second one (Pick some nice colours) takes you to {Project}ActivityDesignerTheme.cs file where you can specify the start and end colours for the gradient. By default it’s dark to light blue.

image

  • The third one (Add validation) takes you to the Validate method in the {Project}ActivityValidator.cs file where you can add any design time validation you need. It even has a sample of how to add a validation failure message.

image

What do I need to add to use it?

Basically all you need to do to get up and running is

1) Add the properties you need to the {Project}Activity.cs file.

2) Add the code as indicated by the task item.

3) Compile and use.

Optionally you can change the colours, add validation, add an icon or change what is shown on the component. The changing of what is shown is controlled via the SetText method in {Project}ActivityDesigner.cs and it has been wired up so that it will respond to property changes. So you can actually have the text change if the properties change with very little code needed.

How do I deploy it?

To use it just dump the ZIP file in the Visual Studio 2008 > Templates> ProjectTemplates > Visual C# in your documents folder and restart Visual Studio!

image

Where can I get it?

 

Note: My hosting provider has something that corrupts zip files so it has been uploaded in 7-zip format which you will need to extract it.

Hopefully you get some productivity benefit from this component or it helps you learn how to write your own, and if it does please leave a comment here so I know (and get that warn fuzzy feeling I like so much).

29 Jan 2009

Dublin - What you need to know!

Dublin is the code name for a application server which will ship as a separate download for Windows server around the .NET 4.0 timeframe. The application server’s focus will be on Workflow Foundation and Windows Communication Foundation applications. So, to me the developer pushing out code today what does it mean?

Well it means that a lot of the grunt work involved with WCF/WF applications is taken away because Dublin will provide a host for them - no more need for IIS for WCF and bespoke solutions for WF. That is not so great, I mean of course you can write your own still and in some situations that will be faster or more scalable than Dublin, but because the host is built the surrounding services come included. So lets take a prime example of how this would effect WF: Currently WF has a great tracking system which you can visualize using WinForms or ASP.NET, but why should I need to “copy-and-paste” that code into every WF application? Why isn’t there an out of the box tool like BizTalk has? Well since the Dublin server will host your workflows they will now provide you with a tool to do it!

Dublin setup/configuration tool

There is some important points to understand here:

  • Dublin is NOT .NET Framework 4 - It’s a separate Windows Server component. Updates will follow the Framework update schedule, but that’s as close as it gets.
  • Dublin is backwards compatible to .NET Framework 3.5 - So the work you are doing today is not wasted.
  • Dublin will support Oslo - Dublin is the first application to support administrators deploying out of Oslo.
  • So do I need BizTalk - Yes. BizTalk will still be great for B2B or LOB integration scenarios where you still will need to write code to get close to those great out of the box features. It is told they will work well together, but I have no details on how yet.
  • So do I need IIS - Yes. Even though a lot of apps now run on IIS will be moved to Dublin, you still want IIS for what it it good for - websites. In addition to that Dublin’s management interface is part of IIS!

Dublin settings in IIS 7.0

  • OS supported - Nothing official I can find but it uses IIS 7.0 so that implies Windows 2008 is a requirement.
  • What will it be called - Nothing offical although the beta bits have Windows Application Server as the name so it looks like it could be that.

Interesting the first customers to start work on Dublin are the Dynamics AX and CRM teams. Since I know CRM let me explain how I think they will use it (nothing official here). In MSCRM 4.0 you have two core components (high level):

  • Async Service - Which runs workflows
  • Web site - Which does the front end and web services

The async service will be dropped and it’s function together with hosting of the web services will be shifted over to Dublin with IIS continuing to host the website!

Persistence Out of the Box!

You can find out more at http://www.microsoft.com/NET/Dublin.aspx

Pictures from: http://www.biztalkgurus.com/blogs/biztalk/archive/2008/11/02/first-look-screen-shots-of-windows-application-server-dublin.aspx

12 Jan 2009

Delphi Prism - Part 1: Opening the "box"

All Prism related posts can be found in the tag Prism.

Hi, my name is Robert. I have been a closet Delphi fan for many years. <Hi Robert>. So when Borland, sorry Interprise, no I was right it’s Borland, sorry I forgot CodeGear, never mind I think it’s no Embarcadero said there was a super duper new version coming I got excited (maybe too much). So I have downloaded the trial and will blog about the experience. Now note Delphi is NOT what I use day to day, in fact if I am choosing a language now it’s C# so don’t expect production evaluations but rather a hackers evaluations. First thing is downloading it (and finding my BDN CDN login) and waiting for the 4Gb to download to the slow internet of South Africa.

So lets see what’s in the box, or image:

image

First is ER/Studio Developer Edition which is a database modeling tool from Embarcadero.

InstallAware Express CodeGear edition is an installer system, ala MSI/InstallShield/NSIS etc…

InterBase 2009 Developer Edition is next, no need to mention what that is (Delphi fans will just know)

Mono is exciting, in there is the Win32 GTK version of Mono :) Cross platform dreams are coming back.

Shell contains the VS 2008 shell install.

Wiki is interesting, as it looks like a dump (dated September 29, 2008) of the one from their site with anything other than read disabled. This makes sense and is actually very useful for us in the slow internet land who may battle to get to the wiki some times. So to who ever had this idea, well done! A few of the articles that jumped out at me are:

  • Win32 Delphi vs. Delphi Prism
  • Delphi Prism Syntax compared with Win32 Delphi
  • Migration Tools: Oxidizer – ShineOn

There is also a good logo:

00b57c86-5c6a-44a3-8d4d-5b1466b70048

06 Jan 2009

Tripping over logs: A story of Unity - Part 6

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.

06 Jan 2009

Tripping over logs: A story of Unity - Part 5

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.

06 Jan 2009

Tripping over logs: A story of Unity - Part 4

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.

06 Jan 2009

Tripping over logs: A story of Unity - Part 3

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.
06 Jan 2009

Tripping over logs: A story of Unity - Part 2

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. Now we are going to take that “nicer” code (compared to the first version) and put Unity in the mix. 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:

Applying Unity

The first step to using Unity is setting it up it, to do that you need to add three references to your solution (highlighted below):

image

Unity has two configuration options, one in code and one in an external configuration file (normally your app/web.config). They both have a use but for this series I will use the configuration file which means you also need to add a reference to:

image

I tend to find that the config file route is what I use in production while the code one is what I use in unit tests (normally to override config file settings).

Next add the references to your code:

using System.Configuration;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

Now in my main method of my application I am going to create an instance of an UnityContainer (line 21 below). This is effectively a magic bag, where we put our hand in and say what we want and pull it out - just like Mary Poppins had. Before we can do that we need to tell it to read the configuration information (lines 23 and 24 below) and then we retrieve the logger (line 26 below) from the magic bag. Note that we are NOT creating an instance of a logger on line 10 below as we did before, the act of pulling the logger out of the bag creates it.

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

Lastly we need to dive into the app.config (add one now if you are following at home) and fight the tangled web of Unity configuration.

Unity Config

We start off by adding a configSection to tell the framework how to handle the new section for Unity (this is lines 3 to 5). Then on line 7 we open our unity tag and the first thing in there is the typeAliases. I recommend using type aliases as they allow you to centrally link a type (like BigSystem.ILogger) to a friendly name. In our example below it’s overkill we could’ve just used the types directly on line 16 (I’ll cover that in a second) but as your solution grows doing find and replace for types is a pain and having this alias system will make life easier. So lines 9 and 10 alias my class and interface to a friendly name.

Now line 13 is where the meat comes in, we open the containers tag which allows up to setup our container which is just a named group of settings. We have one container so we do not need to name it, and in there is the types tag (line 15) which allows us to map what interface to what class, so we we call container.Resolve<ILogger> (line 26 in the code above) it knows what class to return.

   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.DebugLogger, BigSystem"/>
  10:             <typeAlias alias="ILogger" type="BigSystem.ILogger, BigSystem"/>
  11:         </typeAliases>
  12:  
  13:         <containers>
  14:             <container>
  15:                 <types>
  16:                     <type type="ILogger" mapTo="Logger" />
  17:                 </types>
  18:             </container>
  19:         </containers>
  20:     </unity>
  21: </configuration>

So if you run the code it will actually do the logging to the Output window in Visual Studio!

Then if we change line 9 above as such it will output to the console!

<typeAlias alias="Logger" type="BigSystem.ConsoleLogger, BigSystem"/>

This is not super cool because we just made it possible to externally say what class it should use without a recompile of code. You still need to have all the classes in your code already (think ahead) and we have made the logging any better than before. We will really get this improved in part 4 but for now we are moving in the right direction, even if it doesn’t seem like it.

Pages