简体   繁体   中英

Nested Ninject Bindings - Dependency Injection

I have two classes (with similarly named interfaces):

OuterService(IInnerService innerService)

InnerService(string configurationKey)

In my NinjectMvc3 class I have a binding for the IInnerService interface:

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

Right now, I am just copying the constructor instantiation for InnerService within the IOuterService binding:

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

Is there any way that I could avoid this second InnerService constructor by doing a nested/cascading injection with the IInnerService interface?

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

I think ordinary kernel.Bind<IOuterService>().To<OuterService>() should work pretty well for you.

I prepared a small snippet to determine, that if that's really what you want. Is this correct?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM