We use an Ioc Container to resolve most of the objects in a project, however it seems like it might be innappropriate to use it everywhere. At runtime, the user is in the context of a single company Id and it seems appropriate to me to pass that company Id in the constructor of, for example, a repository or unit of work. We could use a parameter override for the company Id at runtime, but is there any benefit in using
var uow = IocContainer.Resolve<IUnitOfWork>(new ParameterOverride("companyId", companyId))
as opposed to
var uow = new UnitOfWork(companyId)
OK, so I understand that I might want to create a different implementation of IUnitOfWork some time and I could then easily swap in the new implementation with Ioc configuration, but I am not convinced I will ever do that anyway.
No, there are times when calling
newis exactly what you want. An example would be an object local to a method call or a narrow scope.Model objects usually aren’t under the control of an IoC container. You instantiate one for each new session or request scope, using data passed to you from users that can never be known by the IoC container on startup.
Update: Honza Brestan’s point about logical units is spot on. The typical Spring layer arrangment is interface-based:
Services use other services, model objects and persistence to fulfill use cases.