Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't Ninject resolve protected properties in a base class?

Simple question I guess, but I've spent an hour trying to get a base class for my controllers to have a few services injected via property injection. The properties were scoped protected at first, but the objects kept coming back null, once I changed the scope to public it worked. Is there anyway to have the properties be protected and get the IoC to work?

Here is my setup.

public class BaseController : Controller
{
    [Inject]
    protected LoggingInterface.ILogger<BaseController> Logger { set; get; }

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

    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        ....

        base.OnAuthorization(filterContext);
    }
}

and the boot-strapper in the NinjectMVC3 App_Start

    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind(typeof(LoggingInterface.ILogger<>)).To(typeof(Log4NetLogger<>));
        kernel.Bind<IRepository>().To<Repository>();
        kernel.Bind<IUserService>().To<UserService>();
    } 

Thank you, Stephen

like image 566
Stephen Patten Avatar asked Nov 07 '11 21:11

Stephen Patten


2 Answers

You cannot inject into properties that do not have public setter. Both your Logger and Repository properties are protected so no way for Ninject to assign them a value. You will have to change their setter visibility if you want to achieve this. Or use constructor injection. While this would make perfect sense for the repository property which seems required it wouldn't make sense for the logger property. So I guess you will have to make it public.

like image 64
Darin Dimitrov Avatar answered Oct 21 '22 07:10

Darin Dimitrov


Pretty sure the InjectNonPublic flag on the NinjectSettings allows you to configure it to do what you want - closest link I can find quickly

Whether it's going to be supported for any significant length of time, I don't know - injecting privates is just a bad idea (along with Property Injection and associated scoundrels :P)

like image 44
Ruben Bartelink Avatar answered Oct 21 '22 06:10

Ruben Bartelink