Two services dependend on eachother (stackoverflow exception) - how to solve?
c#, dependency-injection, design-patterns
Solution
You should not be calling new within your classes, that will tightly couple them. The correct pattern for IOC that will allow you to test each class separately using mocks is:-
public class SiteManager:ISiteManager
{
private readonly IForumManager forumManager;
public SiteManager(IForumManager forumManager)
{
this.forumManager = forumManager;
}
}
public class ForumManager:IForumManager
{
private readonly ISiteManager siteManager;
public ForumManager(ISiteManager siteManager)
{
this.siteManager = siteManager;
}
}
But, that doesn't solve the mutual recursion. The easiest way to solve that is to not use constructor injection for one of the classes, but use property injection instead, i.e. put the SiteManager back to a public property on the ForumManager and set it after creating both objects.
Your setup code then does:-
IForumManager forumManager = new ForumManager();
ISiteManager siteManager = new SiteManager(forumManager);
forumManager.SiteManager = siteManager;
Another alternative would be to pass a ForumManagerFactory into the SiteManager, e.g. a `Func<ISiteManager,IForumManager>`.
ISiteManager siteManager = new SiteManager((s) => new ForumManager(s));
Inside the site manager you can then call the Func, passing `this` to get the IForumManager. The ForumManager gets an instance of the SiteManager and the SiteManager has the ForumManager object.
Problem
I am new to dependency injection, and I am trying to solve an issue. I have two services. Each of these services have methods who need eachother. For instance: `SiteManager` have methods where it needs my `ForumManager`. My `ForumManager` have methods where it needs my `SiteManager`. I have the following two classes: ``` public class SiteManager:ISiteManager { public IForumManager ForumManager { get; set; } public SiteManager() { this.ForumManager = new ForumManager(); } } public class ForumManager:IForumManager { public ISiteManager SiteManager { get; set; } public ForumManager() { this.SiteManager = new SiteManager(); } } ``` Very obviously this will result in a stack overflow exception, as they call eachother. I've read a lot of posts here, and I think I just need a small hint on how to solve this. I have my interfaces in their own assembly. I thought about putting the dependencies in their own property so when they are used, they are made. However, is this best practice? I do not use an IoC container (and I haven't used that before). Any hints on how to solve this particular issue in a "best practice" way! :-)