unity

Adding a static reference into a unity configuration file


Hi,

I’d like to talk about how you can set up your unity configuration file to resolve static references. This is handy depending of the context, for example you would like to register the Path Separator of the file system. This if you’re on unix-based system it’s more likely to be “/” and if you are on a Windows-based system it’s going to be “\”. Certainly you could use configuration files, for this purpose, this is just an alternative where you could let you application know about specific values without knowing they’re coming from, and you usually do this for test-ability.

For those who does not have enough patience, the source code is at https://github.com/hmadrigal/playground-dotnet/tree/master/MsUnity.TypeConverters

The problem

I’d like to set my Unity Container to take the value from a static field, so I do not have to write code to set up a the container in code and in the configuration file.

 

The Solution

Unity Container is very flexible and moreover extensible. It takes advantage of a pattern called “TypeConverter”, which basically it’s an specialized class which maps from one type to another. Particularly in our case we will be mapping from System.string value to any valid static value by using reflection.

Type converters are used along .NET framework, here is a quick guide of How to: Implement a Type Converter:
http://msdn.microsoft.com/en-us/library/ayybcxe5.aspx

In our case, we will assume that we’re receiving a value of type string which follows the following format:

{member}@{assemblyQualifiedName}

Then, we can reference static fields by using the following syntax:

Version@System.Environment, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

The type converter class that does this work is the following:

 

using System;
using System.ComponentModel;
using System.Reflection;

namespace EntLibUnity.Extensions
{
    /// <summary>
    /// Converts an (formatted) string to a reference of a given static member.
    /// The string uses this format: {member}@{assemblyQualifiedName}
    /// For example:
    ///     Version@System.Environment, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
    /// </summary>
    public class StringToStaticInstanceTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return (typeof(string) == sourceType) || base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            string stringValue;
            if (value == null
                || (stringValue = value as string) == null
                || string.IsNullOrEmpty(stringValue)
                || !stringValue.Contains("@")
            )
            {
                return null;
            }

            var stringParts = stringValue.Split('@');
            if (stringParts.Length != 2)
            {
                return null;
            }
            var propertyPath = stringParts[0];
            var propertyPathParts = propertyPath.Split('.');
            var assemblyQualifiedName = stringParts[1];
            // Gets the static member
            var currentClassType = Type.GetType(assemblyQualifiedName, true);
            var currentPropertyInfo = currentClassType.GetProperty(propertyPathParts[0],
                                                                 BindingFlags.Public | BindingFlags.Static |
                                                                 BindingFlags.FlattenHierarchy);
            var currentPropertyValue = currentPropertyInfo.GetValue(null, null);
            // Loops into the path to get a value
            for (var i = 1; i < propertyPathParts.Length; i++)
            {
                currentPropertyInfo = currentClassType.GetProperty(propertyPathParts[i]);
                currentPropertyValue = currentPropertyInfo.GetValue(currentPropertyValue, null);
            }
            return currentPropertyValue ?? base.ConvertFrom(context, culture, value);
        }
    }
}

The second step is to configure our container to recognize the TypeConverter and use it when needed. This is simple, when we’re registering types in the configuration file we have the option of specifying a type converter as you can see in the following sample:

<?xml version="1.0" encoding="utf-8" ?>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <!-- Using Design-Time Configuration: http://msdn.microsoft.com/en-us/library/ff660935(v=PandP.20).aspx#format_config -->
  <!-- The Unity Configuration Schema: http://msdn.microsoft.com/en-us/library/ff660914(v=PandP.20).aspx -->
  <!-- Specifying Types in the Configuration File http://msdn.microsoft.com/en-us/library/ff660933(v=PandP.20).aspx#_Default_Aliases_and-->

  <!-- Setting an alias for our TypeConverter, to prevent using the full type reference -->
  <alias alias="StringToStaticInstanceTypeConverter" type="EntLibUnity.Extensions.StringToStaticInstanceTypeConverter, EntLibUnity.Extensions" />

  <alias alias="IVersionManager" type="EntLibUnity.Infrastructure.IVersionManager, EntLibUnity.UnitySample.ConsoleApp" />
  <alias alias="VersionManager" type="EntLibUnity.UnitySample.VersionManager, EntLibUnity.UnitySample.ConsoleApp" />

  <!-- Default (unnamed) container-->
  <container>
    <register type="IVersionManager" mapTo="VersionManager">
      <constructor>
        <param name="version">
          <!-- In this case we use the expanded version of Param and set the proper typeConverter attribute-->
          <value value="Version@System.Environment, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" typeConverter="StringToStaticInstanceTypeConverter" />
        </param>
      </constructor>
    </register>
  </container>

</unity>

Simple ;-). Finally we only have to use our container as we usually use it. In my case I’ve some extensions to load and configure the container, you can check them by downloading the source code.
Here is the final code of our main application:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using EntLibUnity.Extensions;
using EntLibUnity.Infrastructure;

namespace EntLibUnity.UnitySample.ConsoleApp
{
    class Program
    {
        private static IUnityContainer container;

        static void Main(string[] args)
        {
            container =
                new UnityContainer()
                .LoadContainerFromSection()
                .LoadEnterpriseLibraryTypes();

            var versionManager = container.Resolve<IVersionManager>();
            Console.WriteLine(versionManager.Version);
            Console.ReadKey();
        }
    }
}

The source code is at https://github.com/hmadrigal/playground-dotnet/tree/master/MsUnity.TypeConverters

Your comments are welcome,
kind regards,
Herber

Aspect Oriented Programming and Interceptor design pattern with Unity 2


Hello,

I’ve found a Microsoft article about Unity and Aspect Oriented programming. The article was really interesting. Then, to be the theory in action I’ve decide to exemplify how Unity 2 uses the Interceptor design pattern to support Aspect Oriented Programming (aka AOP).  First of all, let talk about the three key elements involved into this example:

Once again, I’ve decide to use MonoDevelop to create the sample and the source code is available to be downloaded from github at
https://github.com/hmadrigal/playground-dotnet/tree/master/MsUnity.AspectOriented

Sample structure

This example supposes that you have a proxy and want it to add logging information. Thus, we’ve defined a contract (interface) called IProxy to define the expected behavior of our proxy. Then, we have in a separate project an concrete implementation Proxy which implements the interface IProxy. At last but not a least, we have a project which defines a Unity interceptor. All these components are united by the configuration file which lets unity know how these components should interact.

AspectOriented.Infrastructure’s project

This project contains all the common resources and the contracts (interfaces) to be used in the sample. Here is defined the IProxy interface:

using System;
namespace AspectOriented.Infrastructure.Services
{
  public interface IProxy
  {
    bool IsEnabled ();
    void Open ();
    void Close ();
  }
}

AspectOriented.UnityInterceptors’s project

The second project we’re going to talk is where the interceptor is defined. As we’ve already mentioned the interceptor will allow unity to perform tasks before and/or after the intercepted method is invoked. To define  which method is going to be intercepted, we can use two alternatives: 1)a configuration file or 2) by writing some code. I’ll talk about the Unity configuration file once I explain the AspectOriented.Terminal’s project.

using System;
using System.Collections.Generic;
using Microsoft.Practices.Unity.InterceptionExtension;

namespace AspectOriented.UnityInterceptors
{
	public class DiagnosticInterceptor : IInterceptionBehavior
	{
		public DiagnosticInterceptor ()
		{
		}

		#region IInterceptionBehavior implementation
		public IMethodReturn Invoke (IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
		{
			System.Console.WriteLine (String.Format ("[{0}:{1}]", this.GetType ().Name, "Invoke"));

			// BEFORE the target method execution
			System.Console.WriteLine (String.Format ("{0}", input.MethodBase.ToString ()));

			// Yield to the next module in the pipeline
			var methodReturn = getNext ().Invoke (input, getNext);

			// AFTER the target method execution
			if (methodReturn.Exception == null) {
				System.Console.WriteLine (String.Format ("Successfully finished {0}", input.MethodBase.ToString ()));
			} else {
				System.Console.WriteLine (String.Format ("Finished {0} with exception {1}: {2}", input.MethodBase.ToString (), methodReturn.Exception.GetType ().Name, methodReturn.Exception.Message));
			}

			return methodReturn;
		}

		public IEnumerable<Type> GetRequiredInterfaces ()
		{
			System.Console.WriteLine (String.Format ("[{0}:{1}]", this.GetType ().Name, "GetRequiredInterfaces"));
			return Type.EmptyTypes;
		}

		public bool WillExecute {
			get {
				System.Console.WriteLine (String.Format ("[{0}:{1}]", this.GetType ().Name, "WillExecute"));
				return true;
			}
		}
		#endregion
	}
}

As you might noticed the interceptor implements IInterceptionBehavior which will let Unity know that this class can act like an interceptor. To simplify things, the interceptor will print message only when the intercepted method is invoked. The printed information is about the method being invoked. However, interceptors can perform more complex such as starting threads, performing web requests and so on.

AspectOriented.Terminal’s project

This is the main project which generates the executable file. Here are two important things to point out. First we’ve configured our container here. In this case  Unity has being configured by using the configuration file, however you can use code instead. The second, the main application performs calls on the instance that unity resolves, the interception process happens behind scenes and we only will see the result when we call the methods of the proxy.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<configSections>
		<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
	</configSections>
	<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
		<!-- Interception is not part of the default Unity configuration schema. -->
		<!-- Before you can configure interception you must add the correct sectionExtension element to your configuration -->
		<!-- section in the configuration file.-->
		<sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration" />
		<!-- Defines some aliast to easily manipulate the mappings -->
		<alias alias="IProxy" type="AspectOriented.Infrastructure.Services.IProxy, AspectOriented.Infrastructure" />
		<alias alias="Proxy" type="AspectOriented.Terminal.Services.Proxy, AspectOriented.Terminal" />
		<alias alias="DiagnosticInterceptor" type="AspectOriented.UnityInterceptors.DiagnosticInterceptor, AspectOriented.UnityInterceptors" />
		<!-- Default Container when creating the tree-chain of resolution-->
		<container>
			<!-- Loading the section extension only enables the interception configuration to be given in the configuration file. -->
			<!-- Interception itself will not work unless you also load the interception container extension in your Unity container instance.-->
			<extension type="Interception" />
			<register type="IProxy" mapTo="Proxy">
				<lifetime type="ContainerControlledLifetimeManager" />
				<interceptor type="InterfaceInterceptor" />
				<interceptionBehavior type="DiagnosticInterceptor" />
			</register>
		</container>
	</unity>
</configuration>

The configuration file defines two section which are mandatory to define interceptors, these are sectionExtension and extension. Then into the registration of a given type (or in our sample the IProxy Type) we can define the interceptors for this particular type resolution.

using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Configuration;
using AspectOriented.Infrastructure.Services;

namespace AspectOriented.Terminal
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			// Loads the container
			IUnityContainer container = new UnityContainer ();
			container = Microsoft.Practices.Unity.Configuration.UnityContainerExtensions.LoadConfiguration (container);

			// Resolve the proxy-sample
			var proxy = Microsoft.Practices.Unity.UnityContainerExtensions.Resolve<IProxy> (container);
			if (proxy.IsEnabled ()) {
				proxy.Open ();
			}
			proxy.Close ();

			// End of the test
			Console.ReadKey ();
		}
	}
}

At last but not least we’ve our main code. It’s quite straightforward, it creates a Unity container, loads the container configuration from the configuration file, and then uses the container to resolve the given interface (contract). As I mentioned the magic happens behind-scenes, when you call the Proxy methods there is functionality which is going to be injected before and after each call of this instance. Take a look of the final screen-shot to see the all the terminal messages which were triggered during the method calls of the Proxy.

As you can notice the interception calls are injected before and after each call of the intercepted methods of our proxy instance. Furthermore, we can inject the same logic to different contracts (interfaces) by only updating the configuration file. If there is not a contract, it is still possible to perform interception, Unity 2 supports three mechanisms for interception, just keep in mind that each mechanism has its pros and cons.  Remember that same functionality can be plugged to any other component (instance) by using the same mechanism.

Resources about this topic

Once again, I’ve decide to use MonoDevelop to create the sample and the source code is available to be downloaded from github at
https://github.com/hmadrigal/playground-dotnet/tree/master/MsUnity.AspectOriented

Unity 2 Setting up the Chain of Responsability pattern and using a configuration file with Mono (monodevelop)


Unity 2 Setting up the Chain of Responsability pattern and using a configuration file with Mono (monodevelop)

The Chain of Responsibility pattern helps to accomplish two main goals when developing software. It keeps very specific
functionality into separate modules, and by using unity we can decide easily plug and unplug functionality.

If you haven’t heard about Chain of Responsibility pattern see http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern, on the other hand, if you haven’t heard about Microsoft Unity 2 Block (an IoC or dependency injection framework, please check http://unity.codeplex.com/.

Now, lets get started with a simple sample.

1. Get Microsoft Unity 2 Block
I’m going to use mono just to show that it’s possible to use Unity on Mono ;-). So, first of all download Unity Source code from codeplex site at http://unity.codeplex.com/SourceControl/list/changesets# . Once you download the source code, you can remove tests and the compile the project. it should compile properly. (BTW I’m using Mono 2.4)

2. In our sample, the application uses repositories, to get and store user data. Our sample has create a project per layer, and these projects communicate by implementing the interfaces (contracts) from the Infrastructure project. Lets see some notes about each layer.

  • “Data” project will retrieve real data from the data base.
  • “Dummy” project will produce dummy data.
  • “Cache” project will perform cache tasks, and then delegate the data retrival tasks to a given sucessor.
  • “Logging” project will perform logging tasks, and then delegate the data retrival to a give successor.
  • “Infrastructure” project will define the interface that is required for the UserRepository. So all projects knows what is the expected input and output for the UserRepository. Additionally it has been define a ISuccessor interface in order to identify layers that require a successor (for example Logging, Cache).

For the sake of the sample, the IUserRepository defines only one operation GetUserFullName. In this opertion, each implementation will add a text indicating that it has been performed a call to each given layer. By using unity 2 we will be able to indicate which levels will be loaded and executed through a configuration file.

using System;
namespace ChainOfResponsability.Infrastructure.Repository
{
	public interface IUserRepository
	{
		string GetUserFullName(int id);
	}
}

This code is sample of the contract that each different layer is going to implement if they want to be part of the chain for IUserRepository.
Additionally, ISuccessor is defined as following:

using System;
namespace ChainOfResponsability.Infrastructure
{
	public interface ISuccessor<T>
	{
		T Successor {get;}
	}
}

This generic interface allows to indicate a successor to perform the next call in the chain.

3. The “Logging” and “Cache” projects will implement IUserRepository and ISuccessor interfaces, and additionally they will require the successor as parameter of the constructor in order to delegate the task itself. Because of Unity 2 can only resolve one (anonymous) mapping for a given type (always into the same container). My colleague Marvin (aka Murven ) suggested a workaround. Basically, each layer which implements ISuccessor will receive in its constructor the IUnityContainer which will resolve the contract, but instead of using the given container, it will use the parent to resolve the type. So, it could get a different resolution for the same given type.

using System;
using ChainOfResponsability.Infrastructure.Repository;
using ChainOfResponsability.Infrastructure;
using ContainerExtensions = Microsoft.Practices.Unity.UnityContainerExtensions;
using Microsoft.Practices.Unity;
namespace ChainOfResponsability.Logging.Repository
{
	public class LoggingUserRespository : IUserRepository, ISuccessor<IUserRepository>
	{
		public LoggingUserRespository (IUnityContainer container)
		{
			this.Successor = ContainerExtensions.Resolve<IUserRepository> (container.Parent);
		}

		#region IUserRepository implementation
		public string GetUserFullName (int id)
		{
			return string.Format ("{0}->{1}", this.GetType ().Name, this.Successor.GetUserFullName (id));
		}
		#endregion

		#region ISuccessor[IUserRepository] implementation
		public IUserRepository Successor { get; set; }
		#endregion

	}
}
using System;
using ChainOfResponsability.Infrastructure;
using ChainOfResponsability.Infrastructure.Repository;
using Microsoft.Practices.Unity;
using ContainerExtensions = Microsoft.Practices.Unity.UnityContainerExtensions;
namespace ChainOfResponsability.Cache.Repository
{
	public class CacheUserRepository : IUserRepository, ISuccessor<IUserRepository>
	{
		public CacheUserRepository (IUnityContainer container)
		{
			this.Successor = ContainerExtensions.Resolve<IUserRepository> (container.Parent);
		}

		#region IUserRepository implementation
		public string GetUserFullName (int id)
		{
			return string.Format ("{0}->{1}", this.GetType ().Name, this.Successor.GetUserFullName (id));
		}
		#endregion

		#region ISuccessor[IUserRepository] implementation
		public IUserRepository Successor { get; set; }
		#endregion
	}
}

Even though both files owns a similar structure, each file can add a very specific functionality (caching or logging) in the previous example, and the invoke the proper successor.

4. The “Data” and “Dummy” projects will implement IUserRepository only and they will implement the task itself.

using System;
using ChainOfResponsability.Infrastructure;
using ChainOfResponsability.Infrastructure.Repository;
namespace ChainOfResponsability.Dummy.Repository
{
	public class DummyUserRepository : IUserRepository
	{
		public DummyUserRepository ()
		{
		}

		#region IUserRepository implementation
		public string GetUserFullName (int id)
		{
			return string.Format ("{0}[{1}]", this.GetType ().Name, id);
		}
		#endregion
	}
}
using System;
using ChainOfResponsability.Infrastructure;
using ChainOfResponsability.Infrastructure.Repository;
namespace ChainOfResponsability.Data.Repository
{
	public class DataUserRepository : IUserRepository
	{
		public DataUserRepository ()
		{
		}

		#region IUserRepository implementation
		public string GetUserFullName (int id)
		{
			return string.Format ("{0}[{1}]", this.GetType ().Name, id);
		}
		#endregion
	}
}

In the case of “Data” and “Dummy” layers, they don’t need a successor so they can perform the task itself and return the proper result.

6. There is an additional step, which is to load all the containers from the configuration file. Basically it’s done by looping through all the containers and asking for a new child on each iteration. So, we can create a sort of chain of containers where each one owns a different type resolution for the save given type. I’ve created an small utility which load the different containers and create a chain (container and parents).

        public static IUnityContainer container;
	private static void UnityBootStrap()
        {
            container = new UnityContainer();
            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

            #region Mappings based on the configuration file
            IUnityContainer currentContainer = container;
            foreach (var containerSection in section.Containers)
            {
                var nestedContainer = currentContainer.CreateChildContainer();
                Microsoft.Practices.Unity.Configuration.UnityContainerExtensions.LoadConfiguration(nestedContainer, section, containerSection.Name);
                currentContainer = nestedContainer;
            }
            container = currentContainer;
            #endregion
        }

This code loads the configuration file of Unity, and creates a containers which has a parent, and its parent has a different parent and so on. In this way we can create a chain with different mappings to the same IUserRepository contract. Additionally the following configuration file has been defined:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  	<!-- Defines some aliast to easily manipulate the mappings -->
    <alias alias="IUserRepository" type="ChainOfResponsability.Infrastructure.Repository.IUserRepository, ChainOfResponsability.Infrastructure" />
    <alias alias="DataUserRepository" type="ChainOfResponsability.Data.Repository.DataUserRepository, ChainOfResponsability.Data" />
    <alias alias="DummyUserRepository" type="ChainOfResponsability.Dummy.Repository.DummyUserRepository, ChainOfResponsability.Dummy" />
    <alias alias="CacheUserRepository" type="ChainOfResponsability.Cache.Repository.CacheUserRepository, ChainOfResponsability.Cache" />
    <alias alias="LoggingUserRespository" type="ChainOfResponsability.Logging.Repository.LoggingUserRespository, ChainOfResponsability.Logging" />

    <!-- Default Container when creating the tree-chain of resolution-->
    <container>
    </container>
    <!-- lowest level of the resolution chain -->
    <container name="DummyContainer">
      <register type="IUserRepository" mapTo="DummyUserRepository">
        <lifetime type="ContainerControlledLifetimeManager" />
      </register>
    </container>
    <container name="DataContainer">
      <register type="IUserRepository" mapTo="DataUserRepository">
        <lifetime type="ContainerControlledLifetimeManager" />
      </register>
    </container>
    <!-- Middle tiers. They can be added as many as needed, while they implement the proper interface -->
    <!-- Concrete implementations are chained because they're properly implementing ISuccessor interface -->
    <container name="CacheContainer">
      <register type="IUserRepository" mapTo="CacheUserRepository">
        <lifetime type="ContainerControlledLifetimeManager" />
      </register>
    </container>
    <!-- Chain of excution starts here! -->
    <container name="LoggingContainer">
      <register type="IUserRepository" mapTo="LoggingUserRespository">
        <lifetime type="ContainerControlledLifetimeManager" />
      </register>
    </container>
  </unity>
</configuration>

7. Because of we only have a common reference between projects (technically all projects are referencing “Infrastructure”, and some projects are referencing Unity. The final project does not need to reference all the implementations, but we have to copy the DLLs of each layer before running the application. If not, we will receive a message like:
The type name or alias …. could not be resolved. Please check your configuration file and verify this type name.” Assuming that you’ve written correctly all the types and DLLs names, then this error appears because the application couldn’t find the DLLs required to load the specified type. So, remember to copy the DLLs when running the application.

		public static void Main (string[] args)
		{
			UnityBootStrap();
			//var userRepository = Microsoft.Practices.Unity.UnityContainerExtensions.Resolve<IUserRepository>(container);
			var userRepository =  ContainerExtensions.Resolve<IUserRepository>(container);
			Console.WriteLine ("Call Stack of Layers when invoking GetUserFullName(0):\n {0} ", userRepository.GetUserFullName(0));
		}

At last but not least you can modify the configuration file to dynamically chance the layers that will be executed without changing your code. For example our first call will produce”

Calling our Sample with the Data Layer

And we can replace the “Data” layer with the “Dummy” layer just by commenting the “Data” layer definition into the configuration file.

Calling with Dummy Layer

Certainly this could open the door to more complex tasks and scenarios. The full source code of this sample has been hosted in GitHub at
https://github.com/hmadrigal/playground-dotnet/tree/master/MsUnity.ChainOfResponsability

Best regards,
Herber

Microsoft Unity2 Block and Generics into Configuration File


Hi,

I saw a question in stackoverflow about using Microsoft Unity Block to resolve generic types. At first I was surprised because I didn’t know Unity could specify Generics into the configuration file. So, after some research I realize some facts, that I’d like to share with you.

Microsoft Enterprise Libraries 5 is using Unity. The developers were planning to include a editor for the Unity Block, which was available during the beta, but it was removed from the final version. This editor is not the final, but it’s good enough to help you to write your mappings.
Sample of the Unity config file
Now we’re ready to start solving our problem of how to use Unity to resolve interfaces (or contracts) which are using generics. All this by using a configuration file. Lets take a look to the configuration file:

<pre><code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <alias alias="StringListContract" type="System.Collections.Generic.IList`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <alias alias="ConcreteStringList" type="System.Collections.Generic.List`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <container>
      <register type="StringListContract" mapTo="ConcreteStringList">
        <lifetime type="ContainerControlledLifetimeManager" />
        <constructor />
      </register>
    </container>
  </unity>
</configuration></code></pre>

As you can see, configuration is simple. A quick note is that when it’s registered the type resolution IList => List. This resolution specifies a default default constructor. This is because of Unity block cannot determine the best constructor for the List. Additionally this sample is using signed dlls, so the references of IList, List and String are signed.

The last part of this sample, is consuming this configuration file.

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
namespace UnityTerminal
{


    class Program
    {
        static void Main(string[] args)
        {
            var container = new UnityContainer();
            container.LoadConfiguration();
            {
                var concreteStringList = container.Resolve<System.Collections.Generic.IList<System.String>>();
                concreteStringList.Add("Hello World");
            }
            {
                var concreteStringList = container.Resolve<System.Collections.Generic.IList<System.String>>();
                Console.WriteLine("{0}", concreteStringList[0]);
            }
            Console.ReadKey();
        }
    }
}</code></pre>

So, by doing this the first call to resolve will retrieve resolve the type based on the configuration file, the second call is used to verify the implemented behavior by printing the previous stored value.

Best regards,
Herber

Implementing a Plug-in Loader in C# (Using Unity)


Hi,

In my old post I explained a way for implementing plug-in with reflection and IO file operations, and Indeed this is one way for doing it. Currently there are frameworks that can simplify this kind of tasks, and these frameworks are more flexible. Here there are two of frameworks:

Microsoft Extensibility Framework (@  http://mef.codeplex.com/Wikipage)

From codeplex site:

“MEF presents a simple solution for the runtime extensibility problem. Until now, any application that wanted to support a plugin model needed to create its own infrastructure from scratch. Those plugins would often be application-specific and could not be reused across multiple implementations.

  • MEF provides a standard way for the host application to expose itself and consume external extensions. Extensions, by their nature, can be reused amongst different applications. However, an extension could still be implemented in a way that is application-specific. Extensions themselves can depend on one another and MEF will make sure they are wired together in the correct order (another thing you won’t have to worry about).
  • MEF offers a set of discovery approaches for your application to locate and load available extensions.
  • MEF allows tagging extensions with additonal metadata which facilitates rich querying and filtering”

Unity (@ http://unity.codeplex.com/)

From codeplex:

“The Unity Application Block (Unity) is a lightweight extensible dependency injection container with support for constructor, property, and method call injection.

Unity addresses the issues faced by developers engaged in component-based software engineering. Modern business applications consist of custom business objects and components that perform specific or generic tasks within the application, in addition to components that individually address cross cutting concerns such as logging, authentication, authorization, caching, and exception handling.

The key to successfully building such applications is to achieve a decoupled or very loosely coupled design. Loosely coupled applications are more flexible and easier to maintain. They are also easier to test during development. You can mock up shims (lightweight mock implementations) of objects that have strong concrete dependencies; such as database connections, network connections, ERP connections, and rich user interface components. ”

So, are they the same framework?

Although both frameworks struggle to allow a better application extensibility, their attack the problem from different fronts. And of course, each framework has their own set of concepts.

Let prepare a quick plug-in with unity

Before continuing, I’d like to clarify that this is only one approach for using unit, I can bet that there might be more interesting implementations, however mine is really good for getting started ;-). BTW, I’m doing this sample based on this article @ http://www.pnpguidance.net/post/UnityConfigurationSeparateConfigurationFile.aspx I’m going to try to sum up all the step I’ve followed to create this (Unity) plug in. At the end of the post (or sample) the source code will be published for download.

Project Structure

The following are the projects that have been created, and the (relevant) files that each project contains.

Sample.UnityPlugin This is the default project (in this case a console application). This project uses the plug in implementation, although it does not need to know how is the concrete implementation, this project only references to the Sample.UnityPlugin.Contracts.
Sample.UnityPlugin.Contracts This project contains common content between the plug in contract and the plug in implementation. This common content is an interface (aka Contract) which defines what the plugin must provide. This project is referenced by the two parts, the first part if the part of the application that will implement the functionality of the plug in. The second part is the part of the application that will be using the implementation of the plug in.
Sample.UnityPlugin.Cocoa This project represents the plug in implementation. It references to the Sample.UnintyPlugin.Cocoa in order to know the plugin’s contract.

Now,  lets prepare some references:
Sample.UnityPlugin needs to reference the Microsoft.Practices.UnityMicrosoft.Practices.Unity.Configuration, Sample.Unity.Contracts.
Sample.UnityPlugin.Cocoa only needs to reference to Sample.UnityPlugin.Contracts.

Defining the Plug in Contract

To implement our plug in lets start by defining the Contract (interface) in our Sample.UnityPlugin.Contracts project. The following is the contract file:

namespace Sample.UnityPlugin.Contracts
{
    public interface IProvider
    {
        object Connection { get; }
        string Name { get; }
    }
}

The IProvider only defines a “Connection” and a Name. Really simple, isn’t ?

Implementing the plug in

The concrete implementation of the plug in will be in the Sample.UnityPlugin.Cocoa (sorry, I was thinking in a Cocoa provided when I wrote this). So, our concrete implementation will be:

using Sample.UnityPlugin.Contracts;

namespace Sample.UnityPlugin.Cocoa
{
    public class Provider : IProvider
    {
        public Provider(string providerName)
        {
            this.Name = providerName;
        }

        public object Connection { get; set; }

        public string Name { get; set; }
    }
}

As you might notices the implementation references the contract (aka interface), and implements the behavior for this contract.

Consuming the plugin

Now lets add the unity.config file to the Sample.UnityPlugin application. The Unity configuration can be loaded from a configuration file, o being set by code.

<?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>
      <typeAlias alias="string" type="System.String, mscorlib" />
      <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
      <typeAlias alias="IProvider" type="Sample.UnityPlugin.Contracts.IProvider, Sample.UnityPlugin.Contracts" />
      <typeAlias alias="Provider" type="Sample.UnityPlugin.Cocoa.Provider, Sample.UnityPlugin.Cocoa" />
    </typeAliases>
    <containers>
      <container name="container">
        <types>
          <type type="IProvider" mapTo="Provider" >
            <lifetime type="singleton" />
            <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">
              <constructor>
                <param name="providerName" parameterType="string">
                  <value value="The big Cocoa Provider (tm)"/>
                </param>
              </constructor>
            </typeConfig>
          </type>
        </types>
      </container>
    </containers>
  </unity>
</configuration>

In a quick review this configuration file is in charge of making the connection between contract and the concrete implementation, by doing it in a configuration file.
It can be changed any time (by providing the correct files). Please, notices that the configuration file is able to call the Provider constructor and send custom values to it.
Also the application is able to label relations between contracts and implementations, and group them into a container, which can be labeled too.
The last comment is about the location of this file, this file uses Configuration API, so it can be referenced indirectly by your app.config (or web.config), however in this sample it’s being loaded
and referenced directly in the code.

Now lets write our main code that will load the plug in:

using System.Text;
using Microsoft.Practices.Unity;
using System.Configuration;
using Microsoft.Practices.Unity.Configuration;
using Sample.UnityPlugin.Contracts;

namespace Sample.UnityPlugin
{
    class Program
    {
        private static IUnityContainer GetContainer()
        {

            var map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = "unity.config";
            var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            var section = (UnityConfigurationSection)config.GetSection("unity");
            var container = new UnityContainer();
            section.Containers["container"].Configure(container);
            return container;
        }

        static void Main(string[] args)
        {
            IUnityContainer container = GetContainer();
            var myProvider = container.Resolve<IProvider>();
            System.Console.WriteLine("Provider Name:{0}", myProvider.Name);
            System.Console.ReadKey();
        }
    }
}

Get container function will load our custom plugin, and the main function will make use of it.
At this time, this post is quite big, and certainly there is more things that unity can do. I’ll try to provide a plug in implementation using MEF, but in my next post 😉

BTW, I almost forgot … here is the source code (Visual Studio 2010 and Unity 2 beta)
https://github.com/hmadrigal/playground-dotnet/tree/master/MsDotNet.PluginWithUnity
Herberth