tags:

views:

340

answers:

2

In my ASP.net MVC application i need to get the host of the application because I have to distinguish between multiple domains/instances.

In consideration of a good design and testability I do not want to get it like this:

public ViewResult Show(int id)
{
   string host = Request.Url.Host;
   ....
}

Is there a possibility to "inject" it through the constructor.

What would be the cleanest solution for this problem?

+1  A: 

Maybe you don't need "injection" in this case. I think for good testability the cleanest solution will be mocking of your Request. Example (using Moq library):

var request = new Mock<HttpRequestBase>();
request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/any"));

var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(request.Object);

var controller = new YourController();
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
eu-ge-ne
+3  A: 

You could also use some constructors for your controller like so :

public MyController() : this(DefaultHostGetter) { }
public MyController(Func<string> hostGetter)
{
    this.hostGetter = hostGetter;
}

private string DefaultHostGetter() { return this.Request.Url.Host; }

the view action would be :

public ViewResult Show(int id)
{
   string host = this.hostGetter();
   ....
}

you would then be able to test your controller by supplying a different host getter (a mock).

Andrei Rinea
Great challenge for testability! +1!
Andrei Rinea