[英]Cannot Inject Dependencies into ASP.NET Web API Controller using Unity
[英]Asp.net web api with unity The type String cannot be constructed
嗨,我用统一的dll创建一个Web API,当我第一次集成这个API时,我已经遇到了
无法加载文件或程序集'System.Web.Http,版本= 4.0.0.0,区域性=中性,PublicKeyToken = 31bf3856ad364e35'或其依赖项之一。 找到的程序集的清单定义与程序集引用不匹配。 (来自HRESULT的异常:0x80131040)
错误我通过添加解决了它:
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
在Web配置文件中,然后我运行该应用程序,我得到如下错误
无法构造字符串类型。 您必须配置容器以提供该值。
然后我搜索了互联网,并添加了:
[InjectionConstructor]
到构造函数,它ApiController
问题,我正在使用ApiController
我的控制器代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Configuration;
using Microsoft.Practices.Unity;
namespace Check.Api.Controllers
{
public class CommonController : ApiController
{
#region Variables
/// <summary>
/// Business layer of .
/// </summary>
private IBLPIP _blPIP;
private IBLCommon _blCommon;
#endregion
#region Constructor
/// <summary>
/// Constructor of Login API Controller
/// </summary>
/// <param name="auth"></param>
[InjectionConstructor]
public CommonController( IBLCommon blCommon)
{
this._blCommon = blCommon;
}
#endregion
#region Methods
[HttpGet]
public HttpResponseMessage Get_CountryList()
{
try
{
List<Country> CountryList = _blCommon.GetCountryList();
return Request.CreateResponse<List<Country>>(HttpStatusCode.OK, CountryList);
}
catch (Exception ex)
{
LogUtil.Error("LoginServiceController\\Login\n" + ex.Message);
return Request.CreateResponse(HttpStatusCode.NotFound);
}
}
#endregion
}
}
任何人请先帮助我,谢谢。
无法构造字符串类型。 您必须配置容器以提供该值。
该错误表明您正在将字符串传递到一个或多个类的构造函数中(此处未显示)。
解决方案是将Unity配置为将字符串注入到您的类中。
public class SomeType : ISomeType
{
private readonly string someString;
public SomeType(string someString)
{
this.someString = someString;
}
}
string someString = "This is a string value";
container.RegisterType<ISomeType, SomeType>(
"someString", new InjectionConstructor(someString));
字符串和原始类型需要手动注入,因为Unity不知道您要注入哪个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.