使用 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);
}
}