简体   繁体   中英

How to use Unity to resolve JavaScriptSerializer?

I have this in a lot of my MVC controllers:

private JavaScriptSerializer _javaScriptSerializer;
        protected JavaScriptSerializer javaScriptSerializer
        {
            get
            {
                if (_javaScriptSerializer == null)
                {
                    _javaScriptSerializer = new JavaScriptSerializer();
                }

                return _javaScriptSerializer;
            }
            set
            {
                _javaScriptSerializer = value;
            }
        }

I have tried resolving it doing:

<alias alias="JavaScriptSerializer" type="System.Web.Script.Serialization.JavaScriptSerializer, System.Web.Script.Serialization" />

and

<register type="JavaScriptSerializer" mapTo="JavaScriptSerializer" />

But every time I run my application it gives me cannot resolve dependency. Is there a way I can initialize this once throughout my application and now have to initialize it for every controller?

Actually, you don't have to register anything. JavaScriptSerializer is a concrete class with a zero argument constructor, so Unity should just new it up for you, no configuration needed.

So why didn't it work before? When you configured it, you need to use the full assembly name in the alias. You didn't - you left off the version, public key token, and culture fields. As such, the CLR was unable to locate the assembly you asked for and the resolve failed.

Remove the alias and registration from your configuration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM