IoC (Ninject) and Factories

前端 未结 4 1717
长发绾君心
长发绾君心 2020-12-09 03:15

If I have the following code:

public class RobotNavigationService : IRobotNavigationService {
  public RobotNavigationService(IRobotFactory robotFactory) {
          


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 03:40

    For your sample, you have a perfectly fine factory implementation and I wouldn't change anything.

    However, I suspect that your KillerRobot and StandardRobot classes actually have dependencies of their own. I agree that you don't want to expose your IoC container to the RobotFactory.

    One option is to use the ninject factory extension:

    https://github.com/ninject/ninject.extensions.factory/wiki

    It gives you two ways to inject factories - by interface, and by injecting a Func which returns an IRobot (or whatever).

    Sample for interface based factory creation: https://github.com/ninject/ninject.extensions.factory/wiki/Factory-interface

    Sample for func based: https://github.com/ninject/ninject.extensions.factory/wiki/Func

    If you wanted, you could also do it by binding a func in your IoC Initialization code. Something like:

    var factoryMethod = new Func(nameOfRobot =>
                            {
                                if (nameOfRobot == "Maximilian")
                                {
                                    return _ninjectKernel.Get();
                                }
                                else
                                {
                                    return _ninjectKernel.Get();
                                }
    
                            });
    _ninjectKernel.Bind>().ToConstant(factoryMethod);
    

    Your navigation service could then look like:

        public class RobotNavigationService
        {
            public RobotNavigationService(Func robotFactory)
            {
                var killer = robotFactory("Maximilian");
                var standard = robotFactory("");
            }
        }
    

    Of course, the problem with this approach is that you're writing factory methods right inside your IoC Initialization - perhaps not the best tradeoff...

    The factory extension attempts to solve this by giving you several convention-based approaches - thus allowing you to retain normal DI chaining with the addition of context-sensitive dependencies.

提交回复
热议问题