簡體   English   中英

嵌套Ninject綁定-依賴注入

[英]Nested Ninject Bindings - Dependency Injection

我有兩個類(具有類似命名的接口):

OuterService(IInnerService innerService)

InnerService(string configurationKey)

在我的NinjectMvc3類中,我具有IInnerService接口的綁定:

kernel.Bind<IInnerService>.ToMethod(c => new InnerService("myConfigurationKey")))

現在,我只是在IOuterService綁定中復制InnerService的構造函數實例:

kernel.Bind<IOuterService>.ToMethod(c => new OuterService(new InnerService("myConfigurationKey")))

有什么方法可以通過使用IInnerService接口進行嵌套/級聯注入來避免第二個InnerService構造函數?

// I realize this isn't valid, but it may better clarify my intent:
kernel.Bind<IOuterService>.ToMethod(c => new OuterService(IInnerService))

我認為普通kernel.Bind<IOuterService>().To<OuterService>()應該對您來說很好。

我准備了一個小片段來確定是否正是您想要的。 這個對嗎?

using System;
using Ninject;

namespace NinjectTest
{
    class Program
    {
        static void Main(string[] args)
        {
            IKernel kernel = new StandardKernel();

            kernel.Bind<IInnerService>().ToMethod(c=>new InnerService("this is a test config key")); //bind InnerService implementation to be used with provided string
            kernel.Bind<IOuterService>().To<OuterService>(); //bind OuterService implementation to be used, all parameters will be injected to it using previously defined configs

            var outerService = kernel.Get<IOuterService>();

            var result = outerService.CallInner();

            Console.WriteLine(result);
            Console.ReadLine();
        }

        public interface IInnerService
        {
            string GetConfigKey();
        }

        public class InnerService : IInnerService
        {
            private readonly string _configurationKey;

            public InnerService(string configurationKey)
            {
                _configurationKey = configurationKey;
            }

            public string GetConfigKey()
            {
                return _configurationKey;
            }
        }

        public class OuterService : IOuterService
        {
            private readonly IInnerService _innerService;

            public OuterService(IInnerService innerService)
            {
                _innerService = innerService;
            }

            public string CallInner() //purely for testing
            {
                return _innerService.GetConfigKey();
            }
        }   

        public interface IOuterService
        {
            string CallInner();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM