我有一个ASP.NET MVC3网站,我希望能够使用不同类型的电子邮件服务,具体取决于网站的繁忙程度。
请考虑以下事项:
public interface IEmailService
{
void SendEmail(MailMessage mailMessage);
}
public class LocalEmailService : IEmailService
{
public LocalEmailService()
{
// no setup required
}
public void SendEmail(MailMessage mailMessage)
{
// send email via local smtp server, write it to a text file, whatever
}
}
public class BetterEmailService : IEmailService
{
public BetterEmailService (string smtpServer, string portNumber, string username, string password)
{
// initialize the object with the parameters
}
public void SendEmail(MailMessage mailMessage)
{
//actually send the email
}
}
虽然该网站正在开发中,但我的所有控制器都会通过LocalEmailService发送电子邮件;当网站投入生产时,他们将使用BetterEmailService。
我的问题有两个:
1)我究竟如何传递BetterEmailService构造函数参数?它是这样的(来自〜/ Bootstrapper.cs):
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
container.RegisterType<IEmailService, BetterEmailService>("server name", "port", "username", "password");
return container;
}
2)有没有更好的方法 - 即将这些密钥放在web.config或其他配置文件中,以便不需要重新编译网站来切换它正在使用的电子邮件服务?
非常感谢!
答案 0 :(得分:2)
由于在开发和生产之间切换是一个部署'事物',我会在web.config中放置一个标志并按如下方式进行注册:
if (ConfigurationManager.AppSettings["flag"] == "true")
{
container.RegisterType<IEmailService, BetterEmailService>();
}
else
{
container.RegisterType<IEmailService, LocalEmailService>();
}
1)我究竟如何传递BetterEmailService构造函数 参数Δ
您可以使用创建类型的代理注册InjectionFactory
:
container.Register<IEmailService>(new InjectionFactory(c =>
return new BetterEmailService(
"server name", "port", "username", "password")));