Accessing the Ninject Kernel Globally

后端 未结 4 453
名媛妹妹
名媛妹妹 2021-02-05 09:25

This question is not specifically related to Ninject. It\'s more of a general coding question, but I\'m posting it here in case there might be a better way entirely of handling

4条回答
  •  借酒劲吻你
    2021-02-05 10:23

    It sounds like you're needing more of a Factory pattern implementation of Ninject. You could migrate the Kernel from the Global.asax to a Factory class which could be interacted with by the rest of your application.

    Alternatively if you have a situation where a parameter specified at runtime is to determine the interface bindings you could wrap the service. This is a hybrid setup of DI and ServiceLocater, but the ServiceLocater only occurs at service level instantiation, all other layers are coded normally in a DI/IOC pattern.

    MyService : IService1
    {
        public void DoSomething(MyCustomParameter parameter)
        {
            //Builds the Kernel using the supplied parameter
            //We've in our resolver bound IService1 To MyActualService
            var trueService = kernel.Get();
            return trueService.DoSomething(parameter);
        }
    }
    
    MyActualService : IService1
    {
        public void DoSomething()
        {
            //Do the Actual work
        }
    }
    

提交回复
热议问题