使用 Web API 設定 Unity
1.將 Unity 新增到專案中
如果你使用 NuGet, 你可以使用 Unity-package 。在程式包管理器控制檯中執行 Install-Package Unity
。這將為你的專案新增 Unity 庫(及其依賴項)。
2.建立 IDependencyResolver
的實現
例如:
public class UnityResolver : IDependencyResolver
{
protected IUnityContainer Container;
public UnityResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.Container = container;
}
public object GetService(Type serviceType)
{
try
{
return Container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return Container.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}
public IDependencyScope BeginScope()
{
var child = Container.CreateChildContainer();
return new UnityResolver(child);
}
public void Dispose()
{
Container.Dispose();
}
}
3.在你的 WebApiConfig
中註冊你的 IDependencyResolver
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Routes goes here..
// Create your container.
var container = new UnityContainer();
// Do registrations here...
// Assign your container.
config.DependencyResolver = new UnityResolver(container);
}
}