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.
Sorry, MVC is not my league, but is there some reason why you can’t remove the
staticmodifier, set lifetime ofJsonNetSerializerto be singleton, and have that injected into the constructor ofJsonResult? Note in particular this makes the dependency onISerializerexplicit (a good thing) and avoidsstatic(a good thing).