Reputation: 12305
I have read about IOC/DI for dependency injection. It says to create interfaces of every class that we wish to inject. Doesn't it violates the definition of interface(implement where we want to enforce behavior in a class). Any help will be highly appreciated. Thanks.
Upvotes: 0
Views: 99
Reputation: 14700
I think your main point of confusion is that in a DI/IoC scenario, we don't have a class we want to inject, we have a service we want to inject. Let's say I have a Logger
class. It's not the Logger
class itself I want to inject, it's the set of logging services described by the ILogger
interface. If I wasn't using DI or IoC, I would have a place in each class where I would go ILogger _logger = new Logger()
, or maybe ILogger _logger = Logger.Instance
, both of which couple my code to a specific instance of the ILogger
interface. But with DI/IoC, I leave this step to the framework, and don't bother with the specific implementation in my business logic class.
Upvotes: 2
Reputation: 13256
Doesn't it violates the definition of interface(implement where we want to enforce behavior in a class)?
No it doesn't.
The mere fact that you are creating an interface implies that you are defining behaviour. Whether or not you are going to use DI to get to your implementation is not all that relevant.
Upvotes: 1