Simple Injector:Factory classes that need to create classes with dependencies

前端 未结 4 1867
灰色年华
灰色年华 2021-02-14 15:45

I have a factory class that creates a couple of different types of class. The factory is registered with the container. What is the recommended way of creating the classes insid

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-14 16:30

    I agree with @Phil, letting the factory take a dependency on the container is fine, but there's one peace of information missing in his answer.

    You are probably trying to prevent taking a dependency on the container because you try to stay away from the Service Locator anti-pattern. I agree that Service Locator is an anti-pattern and should be prevented.

    Whether or not a dependency on the container is an implementation of the Service Locator anti-pattern depends on where this consumer is defined. Mark Seemann explains this here:

    A DI container encapsulated in a Composition Root is not a Service Locator - it's an infrastructure component.

    So letting your factory depend on the container is fine as long as you define this MyFactory implementation inside your composition root.

    When you do this you'll soon get into trouble since a class that is defined in the composition root can't be referenced from the rest of the application. But that problem is easily solved by defining an IMyFactory interface in the application and letting your factory implementation implement that interface (as you should do anyway to adhere to the Dependency Inversion Principle).

    So your registration would become something like this:

    container.RegisterSingleton();
    

    And the implementation like this:

    private sealed class MyFactory : IMyFactory
    {
        private readonly Container container;
    
        public MyFactory(Container container)
        {
            this.container = container;
        }
    
        public IMyWorker CreateInstance(WorkerType workerType)
        {
            if (workerType == WorkerType.A)
                  return this.container.GetInstance();
    
            return this.container.GetInstance();
        }
    }
    

提交回复
热议问题