0

我正在使用Ninject.Web.Mvc(MVC 2 版本)附加组件和 ASP.NET MVC 2。这是我的摘录Global.asax.cs

protected override void OnApplicationStarted()
{
    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes;
    // RegisterAllControllersIn() is not available in the MVC 2 version of Ninject
}

protected override IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    kernel.Bind<IRepository>().To<NHibernateRepository>();

    return kernel;
}

我也有一个基础RepositoryController

public class RepositoryController : Controller
{
    protected IRepository Repository { get; set; }

    public RepositoryController()
    {

    }

    public RepositoryController(IRepository repository)
    {
        Repository = repository;
    }
}

如您所见,这是一个非常简单的设置,RepositoryController需要注入 的实例IRepository,而 Ninject 被配置为使用NHibernateRepository. 但是,这不起作用,并且Repository每当我尝试在控制器中访问它时该属性为空。但是,如果我将代码更改为此:

[Inject]
public IRepository Repository { get; set; }

然后它工作正常。有谁知道为什么构造函数注入不起作用,但属性注入是?

4

1 回答 1

1

Try removing the parameterless constructor.

Ninject might be picking the wrong constructor to resolve.

To test it out, you could put a breakpoint in both constructors and see which one fires, but I have a feeling it's the parameterless one.

于 2010-10-14T01:10:03.880 回答