Use*_*ser 6 c# dependency-injection castle-windsor
我有这个接口被少数具体类型使用,例如EmailFormatter,TextMessageFormatter等等.
public interface IFormatter<T>
{
T Format(CompletedItem completedItem);
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题EmailNotificationService是,我想要注入EmailFormatter.此服务的构造函数签名是public EmailNotificationService(IFormatter<string> emailFormatter).
我很确定我之前已经看过这个,但我如何在Windsor中注册它,以便EmailFormatter在构造函数参数名称为emailFormatter?时注入?
这是我的温莎注册码.
container.Register(Component.For<IFormatter<string>>().ImplementedBy<EmailFormatter>());
Run Code Online (Sandbox Code Playgroud)
请勿尝试在DI配置中解决此问题.相反,在应用程序的设计中解决它.在我看来,你已经使用相同的界面定义了几个不同的东西.你的要求很明显,因为你说:
我想注入EmailFormatter
你不想注入格式化程序; 你想注入一个电子邮件格式化程序.换句话说,你违反了Liskov替代原则.在应用程序中修复此问题.定义一个IEmailFormatter接口,让EmailNotificationService依赖于此:
public interface IEmailFormatter
{
string Format(CompletedItem completedItem);
}
public class EmailNotificationService
{
public EmailNotificationService(IEmailFormatter formatter)
{
}
}
Run Code Online (Sandbox Code Playgroud)
这有两个重要的优点:
EmailNotificationService实际存在.小智 6
服务代码:
public EmailNotificationService(IFormatter<string> emailFormatter){...}
Run Code Online (Sandbox Code Playgroud)
依赖注册码:
container.Register(
Component.For<IFormatter<string>().ImplementedBy<TextMessageFormatter>().Named("TextMessageFormatter"),
Component.For<IFormatter<string>().ImplementedBy<EmailFormatter>().Named("EmailFormatter"),
Component.For<INotificationService>().ImplementedBy<EmailNotificationService>().ServiceOverrrides(
ServiceOverride.ForKey("emailFormatter").Eq("EmailFormatter"))
);
Run Code Online (Sandbox Code Playgroud)