我正在尝试在我的WebAPI解决方案中使用Unity,并且我正在尝试从web.config文件加载配置。
这是web.config中的统一部分:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<assembly name="MyWebAPI" />
<namespace name="MyWebAPI.Controllers" />
<container>
<register type="MyController" mapTo="MyController">
<constructor>
<param name="param1">
<value value="val1" />
</param>
<param name="param2">
<value value="val2" />
</param>
<param name="param3">
<value value="val3" />
</param>
</constructor>
<lifetime type="singleton" />
</register>
</container>
</unity>
Bootstrapper.cs:
public static IUnityContainer Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
return container;
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
RegisterTypes(container);
return container;
}
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<MyController>();
container.LoadConfiguration();
}
Global.asax:
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
Bootstrapper.Initialise();
}
但这对我不起作用,因为参数没有进入构造函数。
WebAPI控制器构造函数:
public MyController(string param1, string param2, string param3)
{
_param1 = param1;
_param2 = param2;
_param3 = param3;
}
答案 0 :(得分:3)
使用特定于Web API的GlobalConfiguration解析程序而不是MVC DependencyResolver。 e.g:
GlobalConfiguration.Configuration.DependencyResolver =
new UnityDependencyResolver(container);
如果您使用Unity bootstrapper for ASP.NET Web API,则会在安装时为您设置。
答案 1 :(得分:0)
对于Web Api,您的控制器基于ApiController类,您应该使用:
GlobalConfiguration.Configuration.DependencyResolver =
new UnityDependencyResolver(container);
这意味着
DependencyResolver.SetResolver(
new Unity.Mvc3.UnityDependencyResolver(container));
用于将Unity注册为应用程序MVC端的依赖性解析程序。
(如果你想为MVC和WebApi注册Unity,你可以同时拥有这两个语句)
如果您收到System.Web.Http版本错误,请尝试从您的引用中删除System.Web.Http.dll并删除Unit.WebApi。 然后重新添加Unity.WebAPI.5.1 Nuget包,它应该没问题。