【问题标题】:bind to property always return null绑定到属性总是返回 null
【发布时间】:2012-04-12 16:30:02
【问题描述】:

我正在尝试使用 Ninject 将存储库绑定到属性,但总是得到绑定对象的空引用。我将使用下面的代码解释问题。

   public interface IServiceRepository
    {
        User GetUser(string email);
        IQueryable<Statistic> GetStatisticForCurrentMonth(string ip);
        void InsertStatistic(ConversionModel conversionModel);

class ServiceRepository : IServiceRepository
{
//Implementation of the Interface
}

我想在创建课程时将bind the repository above 发送到class below。不幸的是 Repository 对象始终是 null。也许我误解了 Ninject 的工作原理?如何解决问题?

    public class Converter
    {
        [Inject]
        public static IServiceRepository Repository { get; set; }
        private static Converter _converter;

        public static Converter Instance
        {
            get { return _Converter  ?? (_Converter  = new Converter ());
        }
}

Ninject 激活码

private static void RegisterServices(IKernel kernel)
{
   kernel.Bind<IServiceRepository>().ToMethod(context => Converter.Repository);
}   

更新

我尝试过这样重写代码

 public class Converter
    {
        private readonly IServiceRepository _repository;

        public Converter(IServiceRepository repository)
        {
            _repository = repository;
        }

//skip code
}

测试...

    [TestMethod]
    public void ConverterInstanceCreated()
    {           
         using (IKernel kernel = new StandardKernel())
         {                 
             kernel.Bind<IServiceRepository>().To<ServiceRepository>();
             Assert.IsNotNull(kernel.Get<Converter>());
         }
    }

给出异常

Test method PC.Tests.NinjectTest.ConverterInstanceCreated threw exception: 
Ninject.ActivationException: Error activating IServiceRepository
No matching bindings are available, and the type is not self-bindable.
Activation path:
  2) Injection of dependency IServiceRepository into parameter repository of constructor of type Converter
  1) Request for Converter

我刚刚迷路了,我试图了解 Ninject 是如何工作了大约一周但没有任何成功。就我而言,为什么会引发此异常?

还请有人将一个存储库注入的工作示例发布到单例类。

【问题讨论】:

    标签: ninject ninject.web.mvc


    【解决方案1】:

    Ninject 不注入静态数据。将 coynverter 更改为非静态类,并在 ninject 中将其配置为 Singleton。还可以使用构造函数注入并将 repo 设为私有字段。

    现在您可以将转换器注入到您需要的构造函数中。

    【讨论】:

    • 我已经用代码更新了帖子,我仍然无法让它工作:(
    • @Tomas 您的代码仍然显示静态 - 除非您要删除您应该在问题帖子中跟进的问题
    • @Ruben 我已经发布了一个不包含静态的解决方案的更新。
    【解决方案2】:

    即使您使用的是属性注入而不是构造函数注入,我认为它仍然是

    private static void RegisterServices(IKernel kernel)
    {
      kernel.Bind<IServiceRepository>().To<ServiceRepository>();
    }
    

    因为 ninject 仍然只需要知道要映射到接口的具体类型

    我还没有测试过,如果有错误,请见谅。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-29
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多