c# - Web API, Unity and Parameterless Constructor -
i have web api solution , want inject class constructor of controller.
i using unity:
webapiconfig.cs
public static class webapiconfig { public static void register(httpconfiguration config) { var container = new unitycontainer(); container.registertype<idatabaseadapter, databaseadapter>(new hierarchicallifetimemanager()); config.dependencyresolver = new unityresolver(container); config.suppressdefaulthostauthentication(); config.filters.add(new hostauthenticationfilter(oauthdefaults.authenticationtype)); var constraintresolver = new defaultinlineconstraintresolver { constraintmap = { ["apiversion"] = typeof(apiversionrouteconstraint) } }; config.maphttpattributeroutes(constraintresolver); config.addapiversioning(); config.routes.maphttproute( name: "defaultapi", routetemplate: "api/{controller}/{id}", defaults: new { id = routeparameter.optional } ); } } unityresolver
public class unityresolver : idependencyresolver { protected iunitycontainer _container; public unityresolver(iunitycontainer container) { _container = container ?? throw new argumentnullexception("container"); } public object getservice(type servicetype) { try { return _container.resolve(servicetype); } catch (resolutionfailedexception) { return null; } } public ienumerable<object> getservices(type servicetype) { try { return _container.resolveall(servicetype); } catch (resolutionfailedexception) { return new list<object>(); } } public idependencyscope beginscope() { var child = _container.createchildcontainer(); return new unityresolver(child); } public void dispose() { dispose(true); } protected virtual void dispose(bool disposing) { _container.dispose(); } } my controller.
[system.web.http.routeprefix("api/v{version:apiversion}/measurements")] [apiversion("1.0")] public class measurementscontroller : controller { private readonly idatabaseadapter _databaseadapter; [injectionconstructor] public measurementscontroller(idatabaseadapter databaseadapter) { _databaseadapter = databaseadapter; } [maptoapiversion("1.0")] [system.web.http.route("gettrafficlights")] public jsonresult gettrafficlights() { var trafficlights = trafficlightcache.trafficlightcache.trafficlights(); var result = new jsonresult { data = jsonconvert.serializeobject(trafficlights), jsonrequestbehavior = jsonrequestbehavior.allowget }; return result; } [maptoapiversion("1.0")] [system.web.http.route("updatemeasurement")] public async task<httpstatuscoderesult> update(string measurementtoupdate) { var measurement = jsonconvert.deserializeobject<measurement>(measurementtoupdate, new jsonserializersettings { datetimezonehandling = datetimezonehandling.utc }); await _databaseadapter.update(measurement); return new httpstatuscoderesult(httpstatuscode.accepted); } } databaseadapter
public class databaseadapter : idatabaseadapter { public async task<dictionary<int, cacheentry>> measurementcache() { ... } public async task update(measurement measurement) { ... } } idatabaseadapter
public interface idatabaseadapter { task<dictionary<int, trafficlightcache.cacheentry>> measurementcache(); task update(measurement measurement); } the error says no parameterless constructor found. if add empty parameterless constructor never fires constructor includes idatabaseadapter injection calls update result in _databaseadapter being null.
the stack trace is
[missingmethodexception: no parameterless constructor defined object.] system.runtimetypehandle.createinstance(runtimetype type, boolean publiconly, boolean nocheck, boolean& canbecached, runtimemethodhandleinternal& ctor, boolean& bneedsecuritycheck) +0 system.runtimetype.createinstanceslow(boolean publiconly, boolean skipcheckthis, boolean fillcache, stackcrawlmark& stackmark) +119 system.runtimetype.createinstancedefaultctor(boolean publiconly, boolean skipcheckthis, boolean fillcache, stackcrawlmark& stackmark) +247 system.activator.createinstance(type type, boolean nonpublic) +83 system.activator.createinstance(type type) +11 system.web.mvc.defaultcontrolleractivator.create(requestcontext requestcontext, type controllertype) +55 [invalidoperationexception: error occurred when trying create controller of type 'apitest2.controllers.v1.measurementscontroller'. make sure controller has parameterless public constructor.] system.web.mvc.defaultcontrolleractivator.create(requestcontext requestcontext, type controllertype) +178 system.web.mvc.defaultcontrollerfactory.getcontrollerinstance(requestcontext requestcontext, type controllertype) +76 system.web.mvc.defaultcontrollerfactory.createcontroller(requestcontext requestcontext, string controllername) +88 system.web.mvc.mvchandler.processrequestinit(httpcontextbase httpcontext, icontroller& controller, icontrollerfactory& factory) +194 system.web.mvc.mvchandler.beginprocessrequest(httpcontextbase httpcontext, asynccallback callback, object state) +50 system.web.mvc.mvchandler.beginprocessrequest(httpcontext httpcontext, asynccallback callback, object state) +48 system.web.mvc.mvchandler.system.web.ihttpasynchandler.beginprocessrequest(httpcontext context, asynccallback cb, object extradata) +16 system.web.callhandlerexecutionstep.system.web.httpapplication.iexecutionstep.execute() +103 system.web.httpapplication.executestep(iexecutionstep step, boolean& completedsynchronously) +155
you need user apicontroller. not controller.
Comments
Post a Comment