Statistics
| Branch: | Revision:

root / trunk / Pithos.ShellExtensions / IoC.cs @ 5120f3cb

History | View | Annotate | Download (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
        /// <summary>
20
        /// The MEF Container
21
        /// </summary>
22
        public CompositionContainer Container;
23
        
24
        /// <summary>
25
        /// Layily initialized singleton instance of IoC
26
        /// </summary>
27
        static readonly Lazy<IoC> Instance=new Lazy<IoC>();
28

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

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