Set Ninject property to private

719 views Asked by At

I have a project using Ninject. I create an Interface and implement it in another class. Add the below code to register the service

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IArticleContent>().To<ArticleService>().InRequestScope();
}  

Create a web page and write the following code

[Inject]
public IArticleContent _ArticleContentService { get; set; }

Write further code to get the data bound to a control and all works.

I then change the above public declaration to private

[Inject]
private IArticleContent _ArticleContentService { get; set; }

And get

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

After some research i added

new StandardKernel(new NinjectSettings() { InjectNonPublic = true });

to the NinjectWebCommon class under the Start method (also tried with RegisterServices method) but same error. So after further research it either seems i need to do this another way (i.e. within a constructor of my service class) or i need the above code somewhere else.

Could anyone advise how to use a property with Ninject when it set private or the "correct" way to do this?

1

There are 1 answers

0
fishgi On

In addition to setting InjectNonPublic to true, you also need to set InjectParentPrivateProperties to true:

var kernel = new StandardKernel(new NinjectSettings
{
    InjectNonPublic = true,
    InjectParentPrivateProperties = true
});

The reason is the page class itself is in fact used as a parent to a class generated from the corresponding aspx file at runtime.