문제

I'm using the Ninject.Web.Mvc (the MVC 2 version) add-on with ASP.NET MVC 2. This is an excerpt of my 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;
}

I also have a base RepositoryController:

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

    public RepositoryController()
    {

    }

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

So as you can see, it's a very simple setup where RepositoryController expects to be injected with an instance of an IRepository, and Ninject is configured to use a concrete instance of NHibernateRepository. However, this doesn't work and the Repository property is null whenever I try to access it in a controller. However, if I change the code to this instead:

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

Then it works fine. Does anyone know why constructor injection isn't working, but property injection is?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top