0

我有一個ASP.NET MVC3站點,我希望能夠使用不同類型的電子郵件服務,具體取決於站點的繁忙程度。MVC中的Unity Framework構造參數

考慮以下幾點:

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或其他配置文件,使該網站將不需要重新編譯來切換它使用的電子郵件服務?

非常感謝!

回答

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"))); 
+0

好極了,謝謝! – ubersteve

相關問題