Ninject属性绑定,如何正确执行 [英] Ninject property binding, how to do correctly

查看:71
本文介绍了Ninject属性绑定,如何正确执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在测试项目中安装了Ninject(v4.0.30319)软件包进行测试.不幸的是,在下面创建测试代码,ValidateAbuse.Instance.Repository始终为Null.为什么Ninject不将存储库绑定到ValidateAbuse.Repository属性? 某些人可能建议使用构造函数绑定,但由于代码结构,我无法使用它.下面的代码只是示例,我需要找到一种绑定到属性的方法.

总是失败的测试方法

 [TestMethod]
        public void PropertyInjection()
        {
          using (IKernel kernel = new StandardKernel())
          {
              kernel.Bind<ISettingsRepository>().To<SettingsRepository>();
              Assert.IsNotNull(ValidateAbuse.Instance.Repository);
          }
        } 

存储库界面

public interface ISettingsRepository
{
    List<string> GetIpAbuseList();
    List<string> GetSourceAbuseList();  
}

存储库实现

 public class SettingsRepository : ISettingsRepository
    {
        public List<string> GetIpAbuseList()
        {
            return DataAccess.Instance.Abuses.Where(p => p.TypeId == 1).Select(p => p.Source).ToList();
        }

        public List<string> GetSourceAbuseList()
        {
            return DataAccess.Instance.Abuses.Where(p => p.TypeId == 2).Select(p => p.Source).ToList();
        }
    }

我试图将存储库绑定到的类

public class ValidateAbuse 
    {        
        [Inject]
        public ISettingsRepository Repository { get; set; }

        public static ValidateAbuse Instance = new ValidateAbuse();
}

解决方案

Ninject仅在创建对象的实例时绑定该对象的属性.由于您是在创建ValidateAbuse实例而不是Ninject实例,因此它不了解任何信息,因此无法在创建时设置属性值.

您应该从ValidateAbuse中删除静态单例,并允许Ninject将其作为单例进行管理.

kernel.Bind<ValidateAbuse>().ToSelf().InSingletonScope();

然后,当您要求Ninject创建需要ValidateAbuse实例的任何类时,它将始终获得相同的实例.

您似乎不太了解Ninject的工作原理或实现方式,因此建议您阅读Wiki 解决方案

Ninject will only bind properties on an object when it creates an instance of that object. Since you are creating the instance of ValidateAbuse rather than Ninject creating it, it won't know anything about it and therefore be unable to set the property values upon creation.

EDIT:

You should remove the static singleton from ValidateAbuse and allow Ninject to manage it as a singleton.

kernel.Bind<ValidateAbuse>().ToSelf().InSingletonScope();

Then when you ask Ninject to create any class that needs an instance of ValidateAbuse, it will always get the same instance.

It seems like you don't fully understand how Ninject works or how to implement it so I would suggest you read the wiki https://github.com/ninject/ninject/wiki/How-Injection-Works and follow some more basic examples before trying to wire it into an existing application.

这篇关于Ninject属性绑定,如何正确执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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