【发布时间】:2018-11-19 17:31:36
【问题描述】:
我尝试使用 C# DI 方法来实现一些东西。以下是我的代码 sn-p。
public interface IMessageService
{
void Send(string uid, string password);
}
public class MessageService : IMessageService
{
public void Send(string uid, string password)
{
}
}
public class EmailService : IMessageService
{
public void Send(string uid, string password)
{
}
}
以及创建ServiceLocator的代码:
public static class ServiceLocator
{
public static object GetService(Type requestedType)
{
if (requestedType is IMessageService)
{
return new EmailService();
}
else
{
return null;
}
}
}
现在,我用
创建一个测试代码public class AuthenticationService
{
private IMessageService msgService;
public AuthenticationService()
{
this.msgService = ServiceLocator
.GetService(typeof(IMessageService)) as IMessageService;
}
}
但是,看起来,我总是得到GetService() 函数返回的null。相反,我希望通过GetService() 函数获得EmailService 对象,那么如何正确执行呢?
【问题讨论】:
-
对于那些出于任何原因尝试使用这种模式的人,即使是对于复杂系统,请知道服务定位器是anti-pattern,如果您认为需要它,请重新考虑你的设计摆脱它。
-
@CodeNotFound - 当它像这段代码一样返回一个硬编码的类时,你是说它是一种反模式吗?还是你说的更笼统?如果有,为什么?
-
@Enigmativity 我一般来说是这样说的 :) 为什么?由于我在第一条评论中添加的 URL 中的博客文章中解释的所有原因。硬编码分辨率也可能被标记为不好的做法。
-
@CodeNotFound - 我认为这有点过于简单了。一个实现只需要契约(接口)和行为(单元测试)——考虑到这两件事,这个模式运作良好。添加装饰器和动态加载,您可以创建一个经过良好测试的灵活开发环境。我认为如果你只走一半,这是一种反模式。
-
@Enigmativity 和
return new EmailService();丢失了行为(单元测试)。在对使用IMessageService的类进行单元测试时,你如何模拟它。也许我错过了什么
标签: c#