I’m using a factory to create different concrete instances of an interface. One of the concrete instances depends on a service that would normally be injected. The life-cycle of the service is managed by the container. In this case is it OK to inject the container into the factory?
I’m using a factory to create different concrete instances of an interface. One of
Share
I would let the container resolve an abstract factory, factory interface, or factory delegate and inject that into consumers instead.
The factory can then take the service as a dependency, which the factory will resolve.
Update based on comments:
Yes, each object created by the factory would get the same instance of the service (which is normally what I want). If that’s not what you want, inject a service factory into the factory. Some containers offer support for automatically resolving factory delegates, so you might be able to inject
Func<IFooService>.As @SebastianWeber mentioned in the comments, that is not a restriction of all containers. Also, consider if it matters. You could pick the shortest of the two lifespans and use that for both.