1

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!

1 Answer 1

2

Since switching between development and production is a deployment 'thing', I would place a flag in the web.config and do the registration as follows:

if (ConfigurationManager.AppSettings["flag"] == "true")
{
    container.RegisterType<IEmailService, BetterEmailService>();
}
else
{
    container.RegisterType<IEmailService, LocalEmailService>();
}

1) How exactly do I pass the BetterEmailService constructor parameters?

You can register an InjectionFactory with a delegate that creates the type:

container.Register<IEmailService>(new InjectionFactory(c => 
    return new BetterEmailService(
        "server name", "port", "username", "password"))); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.