Statistics
| Branch: | Revision:

root / trunk / Pithos.ShellExtensions / IoC.cs @ 7e26c075

History | View | Annotate | Download (2.2 kB)

1
// <copyright file="IoC.cs" company="GRNet">
2
// This project is open source. Released under the XYZ license
3
// </copyright>
4

    
5
namespace Pithos.ShellExtensions
6
{
7
    using System;
8
    using System.ComponentModel.Composition;
9
    using System.ComponentModel.Composition.Hosting;
10
    using System.Diagnostics;
11
    using System.Reflection;
12
    
13
    /// <summary>
14
    /// The IoC class initializes MEF DI and acts as a service locator.
15
    /// A singleton instance of IoC is provided by Instance
16
    /// </summary>
17
    public class IoC
18
    {
19
        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger("Pithos.Extensions.IoC");
20

    
21
        /// <summary>
22
        /// The MEF Container
23
        /// </summary>
24
        public CompositionContainer Container;
25
        
26
        /// <summary>
27
        /// Layily initialized singleton instance of IoC
28
        /// </summary>
29
        static readonly Lazy<IoC> Instance=new Lazy<IoC>();
30

    
31
        /// <summary>
32
        /// Gets the singleton instance of IoC
33
        /// </summary>
34
        public static IoC Current
35
        {
36
            get { return Instance.Value; }
37
        }
38

    
39
        /// <summary>
40
        /// Initializes a new instance of the IoC from types exported from the executing assembly
41
        /// </summary>
42
        public IoC()
43
        {
44
            var catalog = new AggregateCatalog();
45
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));            
46
            
47
            Container=new CompositionContainer(catalog);
48
        }
49
        
50
        /// <summary>
51
        /// Initializes all imported properties of the target object
52
        /// </summary>
53
        /// <typeparam name="T">Type of the target object</typeparam>
54
        /// <param name="target">The target object</param>
55
        /// <returns>The object with all imported properties initialized</returns>
56
        public T Compose<T>(T target)
57
        {
58
            try
59
            {
60
                Container.ComposeParts(target);
61
                return target;
62
            }
63
            catch (Exception exc)
64
            {
65
                Log.ErrorFormat("Composition Error: {0}",exc);
66
                throw;
67
            }
68
        }
69
    }
70
}