Ninject为什么不解析基类中的受保护属性? [英] Why won't Ninject resolve protected properties in a base class?

查看:73
本文介绍了Ninject为什么不解析基类中的受保护属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这是一个简单的问题,但是我花了一个小时试图为我的控制器获取一个基类,以便通过属性注入来注入一些服务.首先,这些属性的作用域是受保护的,但是一旦我将作用域更改为public,这些对象就会恢复为空.无论如何,是否需要保护这些属性并使IoC起作用?

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?

这是我的设置.

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);
    }
}

和NinjectMVC3 App_Start中的引导程序

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>();
    } 

谢谢你, 斯蒂芬

推荐答案

您不能插入没有公共设置器的属性.您的Logger和Repository属性均受保护,因此Ninject无法为它们分配值.如果要实现此目的,则必须更改其设置者的可见性.或使用构造函数注入.尽管这对于似乎需要的存储库属性非常有意义,但对于logger属性却没有任何意义.因此,我想您必须将其公开.

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.

这篇关于Ninject为什么不解析基类中的受保护属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆