Unity Framework constructor parameters in MVC

Posted by ubersteve on Stack Overflow See other posts from Stack Overflow or by ubersteve
Published on 2012-12-18T22:37:25Z Indexed on 2012/12/18 23:03 UTC
Read the original article Hit count: 264

I have an ASP.NET MVC3 site that I want to be able to use different types of email service, depending on how busy the site is.

Consider the following:

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
    }
}

Whilst the site is in development, all of my controllers will send emails via the LocalEmailService; when the site is in production, they will use the BetterEmailService.

My question is twofold:

1) How exactly do I pass the BetterEmailService constructor parameters? Is it something like this (from ~/Bootstrapper.cs):

    private static IUnityContainer BuildUnityContainer()
    {
        var container = new UnityContainer();
        container.RegisterType<IEmailService, BetterEmailService>("server name", "port", "username", "password");       

        return container;
    }

2) Is there a better way of doing that - i.e. putting those keys in the web.config or another configuration file so that the site would not need to be recompiled to switch which email service it was using?

Many thanks!

© Stack Overflow or respective owner

Related posts about mvc

Related posts about dependency-injection