简单注入器中HttpConfiguration的依赖注入

时间:2017-02-01 11:04:45

标签: c# dependency-injection simple-injector httpconfiguration

我在HelpController

中收到错误消息
  

HelpController类型的构造函数包含参数   name' config'并键入未注册的HttpConfiguration。   请确保已注册HttpConfiguration,或更改   HelpController的构造函数。

是否有其他方法可以解决此问题,因为我使用Configuration来获取Configuration.GetModelDescriptionGenerator();

public class HelpController : Controller
{
    private const string ErrorViewName = "Error";

    public HelpController(HttpConfiguration config)
    {
        Configuration = config;
    }

    public HttpConfiguration Configuration { get; private set; }

    ...

    public ActionResult ResourceModel(string modelName)
    {
        if (!String.IsNullOrEmpty(modelName))
        {
            ModelDescriptionGenerator modelDescriptionGenerator = Configuration.GetModelDescriptionGenerator();
            ModelDescription modelDescription;
            if (modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out modelDescription))
            {
                return View(modelDescription);
            }
        }

        return View(ErrorViewName);
    }
}

1 个答案:

答案 0 :(得分:2)

将构造函数更改为private并放回VS生成的无参数构造函数中。您的HelpController应该是这样的。

public class HelpController : Controller
{
    private const string ErrorViewName = "Error";

    public HelpController()
        : this(GlobalConfiguration.Configuration)
    {
    }

    private HelpController(HttpConfiguration config)
    {
        Configuration = config;
    }


    public HttpConfiguration Configuration { get; private set; }
}