-
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();
}
}