看似循环依赖造成的问题与温莎城堡 [英] Seemingly circular dependencies causing issues with Castle Windsor

查看:435
本文介绍了看似循环依赖造成的问题与温莎城堡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个IUserService(和其他服务),我散装我ServiceInstaller.cs注册:

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

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



我那么我IAuthenticationService,我注册成为我的通用WindsorInstaller.cs文件:

I then I have IAuthenticationService which I register as in my generic WindsorInstaller.cs file:

  container.Register(Component.For(typeof (IAuthenticationService))
                .ImplementedBy(typeof(AuthenticationService)));

现在的事情,直到我添加了一个公共属性正在努力就好了 IAuthenticationService 在我的UserService

Now things were working just fine until I added a public property for IAuthenticationService in my UserService.

似乎有一个圆形dependacy或当事情变得注册的一些时间问题,因为我得到了错误:

It seems there is a circular dependacy or some timing issue of when things get registered, as I am getting the error:

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. 



我怎样才能解决这个问题呢?

推荐答案

您需要或者:


  1. 摆脱你通函依赖(这是首选选项),或

  2. 身边工作,通过使用属性注入,而不是构造函数注入。

使用属性注入(如的史蒂芬的回答),让您无需在创建时提供所有相关性创建类的实例。缺点是,它并不像明显,他们需要做的实例化和全面配置实例的类的用户。

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.

有关如何重构一个很好的解释删除ciruclar依赖看到MISKO Hevery这篇博客文章:

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

  • Circular Dependency in constructors and Dependency Injection

这篇关于看似循环依赖造成的问题与温莎城堡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆