Unity and singletons

I just putted up Unity behind my test project and had some troubles with singletons. There is some misleading information in documentation you should be aware of.

I created one class and one interface, both in same project to save some time.

namespace mytest
    public interface ITest
        string Name { get; set; }

    public class Test : ITest
        public string Name { get; set; }

So, as we can see, it’s nothing special. Now let’s take application configuration file. You can see tag called lifetime there. Example in manual uses "singleton" as type attribute of this tag. Instead of it, to avoid errors, you should use correct name of the LifetimeManager.

<?xml version="1.0" encoding="utf-8" ?>
    <section name="unity" 
" />

          <type type="csharptest.ITest,csharptest"
" />

And now, let’s see my little test code to test Unity and singleton. Point of this code is easy – we are creating Unity container and ask tqo ITest type objects from it. To make sure they are the same we will compare their hash codes.

namespace mytest
    class Program
        static void Main(string[] args)
            IUnityContainer container = new UnityContainer();
            UnityConfigurationSection section;
            section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

            ITest test1 = container.Resolve<ITest>();
            ITest test2 = container.Resolve<ITest>();

I hope it helps you!

Liked this post? Empower your friends by sharing it!
Categories: .NET

View Comments (3)

  • yes, I thought I had it working with "singleton" and suddenly I got errors. Thanks for the quick "point in the right direction"

  • BTW: if you wanted to use the alias, just register it in the unity config-section:


    <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />


  • Thanks for this hint.

    My XML just looks like:

    <register type="..." mapTo="...">

    <lifetime type="..."/>

    what is the functional difference here to your xml using type nodes, not register nodes?

    (i am very new to unity, so sorry if thats a trivial question)



Related Post