3

我正在使用演示 MVC 3 Internet 应用程序模板并安装了 ServiceStack.Host.Mvc NuGet 包。我在 Funq 执行构造函数注入时遇到问题。

以下代码段运行良好:

public class HomeController : ServiceStackController
{
    public ICacheClient CacheClient { get; set; }

    public ActionResult Index()
    {
        if(CacheClient == null)
        {
            throw new MissingFieldException("ICacheClient");
        }

        ViewBag.Message = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}

以下抛出错误

无法创建接口的实例。

public class HomeController : ServiceStackController
{
    private ICacheClient CacheClient { get; set; }

    public ActionResult Index(ICacheClient notWorking)
    {
        // Get an error message...
        if (notWorking == null)
        {
            throw new MissingFieldException("ICacheClient");
        }

        CacheClient = notWorking;

        ViewBag.Message = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}

自从公共财产注入有效以来,这并不是什么大不了的事,但我想知道我错过了什么。

4

1 回答 1

1

请注意,在第二个示例中,您没有构造函数,但确实有方法

public ActionResult Index(ICacheClient notWorking)
{
    ....
}

仅注入构造函数和公共属性是行不通的。您可以将其更改为:

public class HomeController : ServiceStackController
{
    private ICacheClient CacheClient { get; set; }

    public HomeController(ICacheClient whichWillWork)
    {
       CacheClient = whichWillWork;
    }

    ...
}
于 2012-09-15T01:10:50.687 回答