How to use a factory with Dependecy Injection without resorting to using Service Locator pattern

后端 未结 3 1834
故里飘歌
故里飘歌 2021-02-06 18:17

I have a GUI application. In it I allow a user to select from a container-provided list of algorithms. Each algorithm will be kicked off as a background task in another view.

3条回答
  •  悲哀的现实
    2021-02-06 18:53

    Best you create a factory interface like this

    public interface IFooFactory
    {
        IFoo CreateFoo(int someParameter);
    }
    

    For Ninject 2.3 see https://github.com/ninject/ninject.extensions.factory and let it be implemented by Ninject by adding the following configuration.

    Bind().AsFactory();
    

    For 2.2 do the implementation yourself. This implementation is part of the container configuration and not part of your implementations.

    public class FooFactory: IFooFactory
    {
        private IKernel kernel;
        public FooFactory(IKernel kernel)
        {
            this.kernel = kernel;
        }
    
        public ISession CreateFoo(int someParameter)
        {
            return this.kernel.Get(
                new ConstructorArgument("someParameter", someParameter));
        }
    }
    

提交回复
热议问题