Unity 3:该类型没有可访问的构造函数

时间:2013-09-28 13:20:16

标签: inversion-of-control unity-container

我有以下界面和实现

namespace ProjectName.Web
{
    public interface IWebUtil
    {        
    }
}


namespace ProjectName.Web
{
    public class WebUtil : IWebUtil
    {                
    }
}

在我的配置中我有这个注册。我正在使用Unity 3。

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <assembly name="ProjectName.Web" />
  ...
   <register name="WebUtil" type="ProjectName.Web.IWebUtil" mapTo="ProjectName.Web.WebUtil">
     <lifetime type="transient" />    
   </register>
  ...

当我尝试解析此配置时,我收到此错误:

Exception is: InvalidOperationException - The type IWebUtil does not have an accessible       constructor.
-----------------------------------------------
At the time of the exception, the container was:
Resolving ProjectName.Web.IWebUtil,(none)

我试图添加空公共构造函数但没有成功。

有人可以帮忙吗?感谢。

1 个答案:

答案 0 :(得分:2)

第一步是确保您正在加载Unity配置,因为默认情况下不会这样做。要做到这一点:

using Microsoft.Practices.Unity.Configuration;

container.LoadConfiguration();

我假设你已经这样做了。我还将假设您正在尝试使用以下代码解析IWebUtil:

container.Resolve<IWebUtil>();

这会抛出InvalidOperationException,因为IWebUtil被配置为命名注册(名称为“WebUtil”)。因此,要么使用配置的名称解析:

container.Resolve<IWebUtil>("WebUtil");

或者将注册更改为默认(未命名)注册:

<register name="" type="ProjectName.Web.IWebUtil" mapTo="ProjectName.Web.WebUtil">
 <lifetime type="transient" />    
</register>
相关问题