看似循环的依赖导致Castle Windsor的问题

Bla*_*man 2 c# dependency-injection castle-windsor

我有一个IUserService(以及其他服务),我在ServiceInstaller.cs中批量注册:

  container.Register(
                AllTypes.FromAssemblyContaining<UserService>()
                .Where(type => type.Name.EndsWith("Service"))
                .WithService.DefaultInterface()
                .Configure(c => c.LifeStyle.Singleton)
                );
Run Code Online (Sandbox Code Playgroud)

然后,我有IAuthenticationService,我在我的通用WindsorInstaller.cs文件中注册:

  container.Register(Component.For(typeof (IAuthenticationService))
                .ImplementedBy(typeof(AuthenticationService)));
Run Code Online (Sandbox Code Playgroud)

现在一切正常,直到我IAuthenticationService在UserService中添加了一个公共属性.

当事情被注册时,似乎存在循环依赖或某些时间问题,因为我收到错误:

Can't create component 'ABCD.Services.UserService' as it has dependencies to be satisfied.
ABCD.Services.UserService is waiting for the following dependencies:

Services:
- ABCD.Services.Interfaces.IAuthenticationService which was registered but is also waiting for dependencies.

ABCD.Services.AuthenticationService is waiting for the following dependencies:

Services:
- ABCD.Services.Interfaces.IUserService which was registered but is also waiting for dependencies. 
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Erg*_*wun 7

你需要:

  1. 摆脱你的循环依赖(这是首选的选项),或
  2. 通过使用属性注入而不是构造函数注入来解决它们.

使用属性注入(如Steven的答案中所示)允许您创建类的实例,而无需在创建时提供所有依赖项.缺点是,对于类的用户来说,实例化和完全配置实例需要做些什么并不明显.

有关如何重构以消除ciruclar依赖关系的一个很好的解释,请参阅MiškoHevery的这篇博客文章: