我正在尝试在我的 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;
}