【问题标题】:Unity Framework constructor parameters in MVCMVC 中的 Unity Framework 构造函数参数
【发布时间】:2012-12-06 05:32:23
【问题描述】:

我有一个 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 或其他配置文件中,这样就不需要重新编译站点来切换它正在使用的电子邮件服务?

非常感谢!

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 dependency-injection unity-container ioc-container


    【解决方案1】:

    由于在开发和生产之间切换是部署“事情”,我会在 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"))); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多