嵌套的Ninject绑定 - 依赖注入

时间:2015-12-18 17:30:42

标签: c# dependency-injection ninject ninject.web.mvc

我有两个类(具有类似命名的接口):

int i=1

在我的NinjectMvc3类中,我有一个IInnerService接口的绑定:

OuterService(IInnerService innerService)

InnerService(string configurationKey)

现在,我只是在IOuterService绑定中复制InnerService的构造函数实例:

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

有没有办法通过对IInnerService接口进行嵌套/级联注入来避免第二个InnerService构造函数?

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

1 个答案:

答案 0 :(得分:3)

我认为普通的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();
        }
    }
}