我有以下服务:
class Order
interface IOrderService
void SendOrder(Order order)
class SmsOrderService:IOrderService(constructor ISmsService)
class FaxOrderService:IOrderService
class MailOrderService:IOrderService
interface ISmsService
void SendSms(string message,string phone)
class XSmsService
class YSmsService(constructor YSmsServiceConfiguration)
class YSmsServiceConfiguration
string Username
string Password
class OrderManager(constructor IOrderService)
void SendOrderAndLog(Order order)
我需要将 OrderManager 与所有 IOrderService 实现的类一起使用。
我的温莎配置是:
static void Main(string[] args)
{
WindsorContainer container = new WindsorContainer();
// OrderManager implementations
container.Register(Component.For<OrderManager>()
.ImplementedBy<OrderManager>()
.Named("OrderManagerWithSmsService")
.DependsOn(Property.ForKey<IOrderService>().Is<SmsOrderService>()));
container.Register(Component.For<OrderManager>()
.ImplementedBy<OrderManager>()
.Named("OrderManagerWithFaxService")
.DependsOn(Property.ForKey<IOrderService>().Is<FaxOrderService>()));
container.Register(Component.For<OrderManager>()
.ImplementedBy<OrderManager>()
.Named("OrderManagerWithMailService")
.DependsOn(Property.ForKey<IOrderService>().Is<MailOrderService>()));
// IOrderService implementations
container.Register(Component.For<IOrderService>()
.ImplementedBy<SmsOrderService>());
container.Register(Component.For<IOrderService>()
.ImplementedBy<FaxOrderService>());
container.Register(Component.For<IOrderService>()
.ImplementedBy<MailOrderService>());
// ISmsService implementations
container.Register(Component.For<ISmsService>()
.ImplementedBy<YSmsService>()
.DependsOn(Property.ForKey<YSmsServiceConfiguration>().Eq(GetConfiguration()))
.Named("YSmsService")
.LifestylePerThread());
container.Register(Component.For<ISmsService>()
.ImplementedBy<XSmsService>()
.Named("XSmsService")
.LifestylePerThread());
var manager = container.Resolve<OrderManager>("OrderManagerWithSmsService");
manager.SendOrderAndLog(new Order()
{
ProductName = "New York Steak"
});
manager.SendOrderAndLog(new Order()
{
ProductName = "Red Wine"
});
Console.Read();
}
如何使用有效的 Windsor 配置在 OrderManager 中使用 YSmsService?
像这样: container.Resolve("SmsOrderService(YSmsService)"); // 解析确定构造函数参数的键
不是这样的:
var manager = container.Resolve<OrderManager>(new
{
orderService = container.Resolve<IOrderService>( new
{
service = container.Resolve<ISmsService>("YSmsService")
})
});