-
StackOverflow 文档
-
unity-container 教程
-
开始使用 unity-container
-
构造函数注入
interface IService
{
void ProcessRequest();
}
interface IRepository
{
IEnumerable<string> GetData();
}
class HelloWorldRepository : IRepository
{
public IEnumerable<string> GetData()
{
return new[] { "Hello", "World" };
}
}
class HelloWorldService : IService
{
private readonly IRepository repo;
public HelloWorldService(IRepository repo)
{
this.repo = repo;
}
public void ProcessRequest()
{
Console.WriteLine(String.Join(" ", this.repo.GetData()));
}
}
class Program
{
static void Main(string[] args)
{
var container = new UnityContainer()
.RegisterType<IRepository, HelloWorldRepository>()
.RegisterType<IService, HelloWorldService>();
//Unity automatically resolves constructor parameters that knows about.
//It will return a HelloWorldService with a HelloWorldRepository
var greeter = container.Resolve<IService>();
//Outputs "Hello World"
greeter.ProcessRequest();
Console.ReadLine();
}
}