【发布时间】:2018-01-08 01:26:18
【问题描述】:
我在依赖链中有许多服务类(服务 A 依赖于服务 B,服务 B 依赖于服务 C 等);它们的行为由一个公共参数(CountryCode)决定,可能支持的国家是在运行时定义的。
注意:Actor 可以扩展为多个实例(不同的线程),并且一个事件只会由单个 Actor 处理,下面的服务是瞬态的(尽管如果需要我可以考虑更改它)。
目前我有这样的事情:
//This application flow starts off with this class
public class ActorExample
{
private IServiceOne _serviceOne; //Has dependent service
public async Task ProcessAsync(Event event)
{
//This value needs to be passed to _serviceOne and any children
//but we only know its value at runtime.
event.CountryCode;
}
}
public class ServiceOne : IServiceOne
{
private IServiceTwo _serviceTwo; //Has another nested dependency
//Implementation here varies depending on event.CountryCode
public async Task DoSomething()
}
public class ServiceTwo : IServiceTwo
{
//Implementation here varies depending on event.CountryCode
public async Task DoSomething()
}
我想我或许可以将泛型与服务一起使用,因此像这样传递国家/地区代码:
public class ServiceTwo<TCountryCode> : IServiceTwo<TCountryCode>
但是因为我们只有在运行时才有这个值,所以这是不可能的,尤其是在注入服务时。
另一种解决方案是将依赖 CountryCode 的服务注入为 null,然后在构造函数中填充,如下所示:
container.Register(Component.For<IActor>().ImplementedBy<Actor>()
.DependsOn(Dependency.OnValue("CountryCode", null));
但是这看起来很麻烦而且很麻烦,尤其是在嵌套很深的时候。
如果一切都失败了,我可能会考虑在调用函数之前设置商店,但我必须为每个函数都这样做,例如:
_serviceOne.SetCountry(CountryCode).DoSomething();
注意:我们将城堡用于 IOC
【问题讨论】:
标签: c# dependency-injection castle-windsor actor chain