开发者

How do I use Ninject to inject a static property?

开发者 https://www.devze.com 2023-01-26 05:12 出处:网络
I\'m using ASP.NET MVC 2 to implement a web service and I have a custom JsonResult class: public abstract class JsonResult : ActionResult

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

精彩评论

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