I tried to use C# DI method to implement something. following is my code snippet.
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)
{
}
}
and code that creates a ServiceLocator
:
public static class ServiceLocator
{
public static object GetService(Type requestedType)
{
if (requestedType is IMessageService)
{
return new EmailService();
}
else
{
return null;
}
}
}
now, I create a test code with
public class AuthenticationService
{
private IMessageService msgService;
public AuthenticationService()
{
this.msgService = ServiceLocator
.GetService(typeof(IMessageService)) as IMessageService;
}
}
but, it looks like, I always get null
returned by GetService()
function. Instead I expect to get EmailService
object via GetService()
function, so how to do it correctly?