开发者

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 containe开发者_Go百科r. 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 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜