【问题标题】:Asp.net web api with unity The type String cannot be constructedasp.net web api with unity 无法构造String类型
【发布时间】:2018-01-31 07:11:03
【问题描述】:

嗨,我正在用统一 dll 创建一个 web api,当我第一次集成这个时,我遇到了

无法加载文件或程序集“System.Web.Http,Version=4.0.0.0,Culture=neutral,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 我的控制器代码如下

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

    }
}

任何人请帮助我提前谢谢。

【问题讨论】:

    标签: c# asp.net-web-api dependency-injection inversion-of-control unity-container


    【解决方案1】:

    无法构造字符串类型。您必须配置容器以提供此值。

    该错误表明您正在将一个字符串传递给一个或多个类的构造函数(此处未显示)。

    解决方案是配置 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 不知道您打算注入哪个字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多