Click here to Skip to main content
12,398,000 members (50,503 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

5.7K views
2 bookmarked
Posted

Object Factory in Unity 2.x

, 6 Dec 2012 Apache
Rate this:
Please Sign up or sign in to vote.
A couple of days ago I spent some time trying to find how to make Unity call a factory method when user requests an object. Then I forgot about it, and tried to Google it again.

A couple of days ago I spent some time trying to find how to make Unity call a factory method when user requests an object. Then I forgot about it, and tried to Google it again. This stuff is surprisingly hard to find, especially given the fact that the method used in Unity 1.x (StaticFactoryExtension) was declared obsolete in favor of InjectionFactory which for whatever reason Unity authors consider “much easier” to use.

Anyway, here’s a full working example, mostly for my future reference:

using System;
using Microsoft.Practices.Unity;

namespace UnityObjectFactory
{
    class Program
    {
        static void Main(string[] args)
        {
            var container = new UnityContainer();
            var factory = container.Resolve<OrderFactory>();
            container.RegisterType<IOrder>(
                new InjectionFactory(unused_container=>factory.CreateOrder()));

            var order1 = container.Resolve<IOrder>();
            Console.WriteLine("Fisrt order has number " + order1.Number);

            var order2 = container.Resolve<IOrder>();
            Console.WriteLine("Second order has number " + order2.Number);
        }
    }

    interface IOrder
    {
        int Number { get; }
    }

    class Order : IOrder
    {
        public Order(int number) { Number = number; }
        public int Number { get; private set; }
    }

    class OrderFactory
    {
        int _lastOrder;

        public IOrder CreateOrder()
        {
            return new Order(++_lastOrder);
        }
    }
}


License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0

Share

About the Author

Ivan Krivyakov
Technical Lead Thomson Reuters
United States United States
Ivan is a hands-on software architect/technical lead working for Thomson Reuters in the New York City area. At present I am mostly building complex multi-threaded WPF application for the financial sector, but I am also interested in cloud computing, web development, mobile development, etc.

Please visit my web site: www.ikriv.com.

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160721.1 | Last Updated 6 Dec 2012
Article Copyright 2012 by Ivan Krivyakov
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid