Option 1: Register Using a Lambda
In this option, rather than registering the email server type directly, register using a lambda expression. This allows you to resolve things from the container or use the environment to get the value.
var builder = new ContainerBuilder(); builder.Register(ctx => { var address = Environment.GetEnvironmentVariable("SERVER_ADDRESS"); return new EmailServer(address); }).As<IEmailServer>();
As part of this, you may want to create some sort of abstraction around how you get the server address. For example, it may be something that you got as part of a web request and you’ve stored it in the HttpContext. You could create an address provider like this:
public interface IServerAddressProvider { string GetServerAddress(); } public class ContextServerAddressProvider : IServerAddressProvider { private HttpContextBase _context; public ContextServerAddressProvider(HttpContextBase context) { this._context = context; } public string GetServerAddress() { return (string)this._context.Items["EMAIL_SERVER_ADDRESS"]; } }
Once you have a provider, you could register that with the container and use it in conjunction with the lambda.
var builder = new ContainerBuilder(); builder.RegisterType<ContextServerAddressProvider>() .As<IServerAddressProvider>() .InstancePerRequest(); builder.Register(ctx => { var address = ctx.Resolve<IServerAddressProvider>().GetServerAddress(); return new EmailServer(address); }).As<IEmailServer>();
If you need to pass a string parameter or can’t modify the code, this is the recommended option.