1

我有以下接口和实现

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)

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

有人可以帮忙吗?谢谢。

4

1 回答 1

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>
于 2013-09-30T13:57:08.433 回答