Ninject property binding, how to do correctly

别说谁变了你拦得住时间么 提交于 2019-12-11 06:49:20

问题


I have installed Ninject (v4.0.30319) package in test project to test. Create test code below, unfortunately ValidateAbuse.Instance.Repository is always Null. Why Ninject do not bind repository to ValidateAbuse.Repository property? Some of you may suggest to use constructor binding but I can't use it due to code structure. The below code is just example and I need to find a way to bind to property.

Test method which always fail

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

The repository interface

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

The repository implementation

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

The class to which I am trying to bind repository

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

        public static ValidateAbuse Instance = new ValidateAbuse();
}

回答1:


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.



来源:https://stackoverflow.com/questions/10188451/ninject-property-binding-how-to-do-correctly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!