0

我知道这是最常遇到的错误之一,但我真的很难解决它。我的控制器上有一个属性: private readonly ISelectListFactory _selectFactory; 以及一个调用来填充 viewbag private void PopulateLists() { var continent = _selectFactory.GetItems(); } 和界面的方法

public interface ISelectListFactory
{
    IEnumerable<SelectListItem> GetItems();

}

在控制器构造函数中,我有以下内容:

public LocationController(ISelectListFactory selectFactory)
    {
        _selectFactory = selectFactory;
     }

但我收到此错误 Object reference not set to an instance of an object 并且不知道如何克服它。

问候

4

1 回答 1

1

确保您已在某处实例化此_selectFactory变量。例如:

_selectFactory = new SomeConcreteSelectListFactory();

或者如果您使用依赖注入,您可以配置您的 DI 框架以将其注入到构造函数中:

public class HomeController: Controller
{
    private readonly ISelectListFactory _selectFactory;
    public HomeController(ISelectListFactory selectFactory)
    {
        _selectFactory = selectFactory;
    }

    ... some controller actions where you could use the _selectFactory field
}
于 2013-08-11T17:18:57.620 回答