views:

245

answers:

3

Hey All.

I have my own inherited App.Controller from Mvc.Controller which then all of my controllers inherit from. I wrote a provider utilizing an interface and implemented it as MyService and the constructor takes the Server property of Mvc.Controller which is of HttpServerUtilityBase.

However, I instantiate MyService in App.Controller's constructor. The problem is that the Server property of the Controller is null when constructing MyService. I have used public Controller () : base() { } to get the base to be constructed. However, Server remains null.

I would like to avoid Web.HttpContext.Current.Server if possible.

Has any one have a work around for this problem?

Edit: Well, I have implemented tvanfosson's suggestion, and when my app constructs MyService in the property get method, Server is still null.

Edit 2: Nevermind, I was a goof. I had another Controller using Server aswell and did not change that. Case closed.

A: 

I instantiate MyService in App.Controller's constructor.

There's your problem. You need to pass an instance of MyService which has already been constructed into your App.Controller's constructor. Take a look at the Inversion of Control / Dependency Injection patterns, and take a look at some of the libraries which make these patterns easy (see this list).

Justice
I'm pretty sure that the controller is instantiated using the default constructor by the ASP.NET runtime. I don't think you'll be able to use an IoC container to create controllers in the same way that you would your business objects.
tvanfosson
ASP.NET MVC is very pluggable, and you can either write your own ControllerFactory or use one from a library. I like Autofac, so I tell ASP.NET MVC to use Autofac's ControllerFactory. Autofac autowires the arguments to my controllers' constructors, and the constructors are free of all "dirtiness."
Justice
+1  A: 

Use delayed initialization to construct your service.

private MyService service;
public MyService Service
{
    get
    {
         if (this.service == null)
         {
             this.service = new MyService(this.Server);
         }
         return this.service;
    }
}

Then, your service isn't actually instantiated until it is used in the controller action and by that time the Server property has been set.

tvanfosson
I like this idea...
Daniel A. White
Or override Controller.Initialize, which fires at the right time.
Craig Stuntz
The best part of delayed initialization is that it doesn't ever happen if the property is never accessed.
tvanfosson
A: 

Why do you need the Server reference? Are you doing stuff like url/html encoding? If so, you could use HttpUtility instead and get rid of the context reference entirely.

Chris Hynes
I am using Server.MapPath.
Daniel A. White