Seemingly circular dependencies causing issues with Castle Windsor

半腔热情 提交于 2019-11-29 15:38:56
Ergwun

You need to either:

  1. Get rid of your circular dependencies (this is the preferred option), or
  2. Work around them, by using property injection, rather than constructor injection.

Using property injection (as illustrated in Steven's answer) allows you to create instances of your classes without providing all the dependencies at the time of creation. The downside is that it is not as obvious to users of the class what they need to do to instantiate and fully configure the instance.

For a nice explanation of how to refactor to remove a ciruclar dependency see this blog post by Miško Hevery:

Property injection will solve your problem, because it breaks the dependency cycle. Just look at Krzysztof's example and try to instantiate a UserService; You can't. Now take a look at the following example:

public class UserService
{
    UserService(AuthenticationService a) { }
}

public class AuthenticationService 
{
    AuthenticationService() { }

    public UserService UserService { get; set; }
}

In this example, the UserService dependency of the AuthenticationService is 'promoted' from a constructor argument to a property. Now you can create a user service like this:

var a = new AuthenticationService();
var s = new UserService(a);
a.UserService = s;

Breaking the circular dependency can be done with property injection and any dependency injection framework can be configured to allow property injection.

here's your scenario as I understand it:

public class UserService
{
   UserService(AuthenticationService a){}
}

public class AuthenticationService 
{
   AuthenticationService (UserService a){}
}

How would you create instances of both classes, creating at most single instance of each class?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!