-
StackOverflow 文档
-
unity-container 教程
-
开始使用 unity-container
-
Hello World
interface IGreeter
{
void Greet();
}
class Greeter : IGreeter
{
public void Greet()
{
Console.WriteLine("Hello World");
}
}
class SpanishGreeter : IGreeter
{
public void Greet()
{
Console.WriteLine("Hola Mundo");
}
}
class FrenchGreeter : IGreeter
{
public void Greet()
{
Console.WriteLine("Bonjour le Monde");
}
}
class Program
{
static void Main(string[] args)
{
var container = new UnityContainer()
.RegisterType<IGreeter, SpanishGreeter>("spanish")
.RegisterType<IGreeter, FrenchGreeter>("french")
.RegisterType<IGreeter, Greeter>();
//Get default registration. Outputs "Hello World"
var greeter = container.Resolve<IGreeter>();
greeter.Greet();
//Get specific named registration. Outputs "Hola Mundo"
greeter = container.Resolve<IGreeter>("spanish");
greeter.Greet();
//Get all named registrations (excludes the default one)
//Outputs "Hola Mundo" and "Bonjour le Monde"
foreach (var g in container.ResolveAll<IGreeter>())
{
g.Greet();
}
Console.ReadLine();
}
}