IOC/DI: Is Registering a Concrete Type a Code Smel

2019-01-26 14:51发布

问题:

I've been struggling with this a bit on my current project. I've come across some cases where I have a concrete type that does not (and does not need) to implement any specific interface. Sometimes I want resolution to happen via the container because the type is registered with singleon lifecycle; sometimes the type has constructor parameters that are part of a larger object graph or are themselves registered with singleton lifecycles.

It always feels a bit strange to me when I type code like:

Container.RegisterType<MyConcreteType, MyConcreteType>();

Any thoughts on whether this is a code smell or violates best practices for using an IOC container?

回答1:

IoC container is an Inversion of Control container, not Abstraction Container or Interface to Implementation Container. It is perfectly legitimate to map classes to themselves and having the container manage their lifetime.

If your design does not call for using interfaces, don't force them. Doing that would be a design smell, namely needless complexity.

I think of IoC containers as factories on steroids. Not every factory is an abstract factory (e.g. singletons). Hence not every registration in IoC container has to be an implementation to abstraction mapping.