0

Ninject を使用してリポジトリをプロパティにバインドしようとしていますが、常にバインディング オブジェクトの null 参照を取得します。以下のコードを使用して問題を説明します。

   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 aboveclass 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が約1週間うまく機能していないことを理解しようとしています. 私の場合、なぜこの例外がスローされるのですか?

また、シングルトン クラスへの 1 つのリポジトリ インジェクションを使用した作業例を投稿してください。

4

2 に答える 2

2

Ninject はスタティックを注入しません。coynverter を非静的クラスに変更し、ninject でシングルトンとして構成します。また、コンストラクター インジェクションを使用して、レポをプライベート フィールドにします。

これで、必要な場所にコンバーターをコンストラクターに挿入できます。

于 2012-04-11T22:48:26.190 に答える