c# - Unity, injecting instances to controller gives seemingly unrelated exception -
this want able (passing interface(s) controllers):
public class testcontroller : controller { // get: test [httpget] public actionresult index(itestservice service) { var test = new testmodel(); test.greeting = "yo" + service.getstring(); test.name = "nils"; return view(test); } }
this have put in global.asax.cs in application_start() try make work:
// create new unity dependency injection container var unity = new unitycontainer(); unity.registertype<itestservice,testservice>(); // finally, override default dependency resolver unity dependencyresolver.setresolver(new ioccontainer(unity));
i have also, can see, created ioccontainer class looks follows:
public class ioccontainer : idependencyresolver { private readonly iunitycontainer _container; public ioccontainer(iunitycontainer container) { _container = container; } public object getservice(type servicetype) { if (_container.isregistered(servicetype)) return _container.resolve(servicetype); return null; } public ienumerable<object> getservices(type servicetype) { if (_container.isregistered(servicetype)) return _container.resolveall(servicetype); return new list<object>(); } public void dispose() { _container.dispose(); } }
when try access "http://humptidumptiurl/test"
tells me:
a public action method 'login' not found on controller 'companyname.product.web.controllers.testcontroller'.
now... thought should resolve itestservice.. not bother different controller? other controllers not use unity yet, work have done....
inputs on how achieve desired solution appriciated
edit:
thank you! of course injects through constructor... should have thought of that... gives me error message:
{"an error occurred when trying create controller of type 'stimline.xplorer.web.controllers.testcontroller'. make sure controller has parameterless public constructor."}
edited testcontroller:
public class testcontroller : controller { private readonly itestservice _testservice; public testcontroller(itestservice service) { _testservice = service; } // get: test [httpget] public actionresult index() { var test = new testmodel(); test.greeting = "yo" + _testservice.getstring(); test.name = "nils"; return view(test); } }
you're injecting dependency action method.
when using idependencyresolver
in manner tend inject dependencies constructor.
try changing controller this:
public class testcontroller : controller { private readonly itestservice service; public testcontroller(itestservice service) { this.service = service; } // get: test [httpget] public actionresult index() { var test = new testmodel(); test.greeting = "yo"; test.name = "nils"; // todo itestservice // this.service.dosomethingcool() return view(test); }
}
Comments
Post a Comment