mat-mcloughlin
mat-mcloughlin

Reputation: 6722

Dependency Injection Circular Dependency

I've started a new project and have been gradually building my service layer up using ninject and the unit of work pattern. I've come across a problem and am looking for some help.

I have a LicenceService that requires access to the UserService so the constructor is

public LicenceService(IRepository<Licence> licenceRepo, IUserService userService)

however I'm now in the situation where my UserService needs access to the LicenceService so the constructor would be

public UserService(IRepository<User> userRepo, ILicenceService licenceService)

I'm guessing by this point you can see my circular reference problem. As Imagine this is not an uncommon problem does anybody have any suitable solutions.

Upvotes: 1

Views: 186

Answers (2)

TheCodeKing
TheCodeKing

Reputation: 19230

You can solve this with a factory or delegate, but really it's a design issue. See if you can factor out some code into a third class to remove the circular dependencies.

Upvotes: 3

Wayne Cornish
Wayne Cornish

Reputation: 635

How about a third service to hold references to both and communicate between them?

That is to say that the third service would call both, for specific purposes, rather than one having to know about the other.

Upvotes: 3

Related Questions