Seemingly circular dependencies causing issues with Castle Windsor

后端 未结 3 1352
隐瞒了意图╮
隐瞒了意图╮ 2020-12-21 12:52

I have a IUserService (and other services) that I am registering in bulk in my ServiceInstaller.cs:

  container.Register(
                AllTypes.FromAssemb         


        
3条回答
  •  误落风尘
    2020-12-21 13:54

    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.

提交回复
热议问题