Beispiel zu Microsofts Dependency Injection Framework Unity

Thomas Darimont

Erfahrenes Mitglied
Hallo,

hier mal ein einfaches Beispiel dazu wie man das neue Dependency Injection Framework Unity von Microsoft verwendet:

http://www.codeplex.com/unity

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;

namespace De.Tutorials.Unity
{
    public class Program
    {
        static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer().Register<IFoo, Foo>();
            Bar bar = container.Get<Bar>();
            Console.WriteLine(bar);
        }
    }

    public interface IFoo{}

    public class Foo : IFoo{}

    public class Bar
    {
        [Dependency]
        public IFoo Foo { get; set; }

        public override string ToString()
        {
            return "Foo: " + Foo;
        }
    }
}

Ausgabe:
Code:
Foo: De.Tutorials.Unity.Foo

Die API fühlt sich ein wenig so an wie die von Googles Guice:
http://code.google.com/p/google-guice/

Gruß Tom
 
Zurück