Daniel T.
Daniel T.

Reputation: 38400

How do I use Ninject to inject a static property?

I'm using ASP.NET MVC 2 to implement a web service and I have a custom JsonResult class:

public abstract class JsonResult : ActionResult
{
    public static ISerializer Serializer { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        var json = Serializer.Serialize(this);
        context.HttpContext.Response.Write(json);
    }
}

JsonResult is the abstract base class for all results that should be serialized into JSON data. It usesan ISerializer to do the serialization.

I'm using Ninject as my IoC container. However, I'm not really sure how I should be injecting the ISerializer dependency. I was originally doing this:

var kernel = new StandardKernel().Bind<ISerializer>().To<JsonNetSerializer>();
JsonResult.Serializer = kernel.Get<ISerializer>();

But something about it just doesn't seem quite right. So how would I go about injecting the Serializer property correctly? I want to inject it only once when the application starts up.

Upvotes: 3

Views: 2243

Answers (1)

jason
jason

Reputation: 241641

Sorry, MVC is not my league, but is there some reason why you can't remove the static modifier, set lifetime of JsonNetSerializer to be singleton, and have that injected into the constructor of JsonResult? Note in particular this makes the dependency on ISerializer explicit (a good thing) and avoids static (a good thing).

Upvotes: 4

Related Questions