c# - Autofac not auto wiring properties to a custom class -
i trying setup class using autofac autowired properties custom class controller calls. have setup test project show this. have 2 projects in solution. mvc web application , class library services. here's code:
in service project, accountservice.cs:
public interface iaccountservice { string doathing(); } public class accountservice : iaccountservice { public string doathing() { return "hello"; } }
now rest in mvc web project.
global.asax.cs
var builder = new containerbuilder(); builder.registercontrollers(assembly.getexecutingassembly()).propertiesautowired(); builder.registerassemblytypes(typeof(accountservice).assembly) .where(t => t.name.endswith("service")) .asimplementedinterfaces().instanceperrequest(); builder.registertype<test>().propertiesautowired(); builder.registerfilterprovider(); var container = builder.build(); dependencyresolver.setresolver(new autofacdependencyresolver(container));
test.cs:
public class test { //this null when var x = "" breakpoint hit. public iaccountservice _accountservice { get; set; } public test() { } public void dosomething() { var x = ""; } }
homecontroller.cs
public class homecontroller : controller { //this works fine public iaccountservice _accountservicetest { get; set; } //this works fine public iaccountservice _accountservice { get; set; } public homecontroller(iaccountservice accountservice) { _accountservice = accountservice; } public actionresult index() { var t = new test(); t.dosomething(); return view(); } //... }
as can see code above, both _accountservicetest
, _accountservice
work fine in controller, when setting break point in dosomething()
method of test.cs
, _accountservice
null, no matter put in global.asax.cs
.
when create object new
autofac not know object. it's normal null iaccountservice
.
so proper way this: set interface test class , register it. add interface homecontroller constructor.
public homecontroller(iaccountservice accountservice,itest testservice)
Comments
Post a Comment