c# - property injection using autofac 3.1.1 -
i trying inject through property in following service, if try constructor injection works want property injection, missing?
public class sodaservice { public isoda _s; //public sodaservice(isoda s) //{ // _s = s; //} public string getsoda() { return _s.sodaname; } } //soda class implementing isoda public class soda : isoda { public string sodaname { { return "default soda"; } } } public interface isoda { string sodaname { get; } } //main calling program class program { static void main(string[] args) { var container = getcontainer(); sodaservice s=container.resolve<sodaservice>(); console.write(s.getsoda()); console.read(); } private static icontainer getcontainer() { var builder = new containerbuilder(); builder.registertype<soda>().as<isoda>(); builder.registertype<sodaservice>() .propertiesautowired(); var container = builder.build(); return container; } }
edit: above solved , have 1 more question....
how can make work, not want use s = container.resolve< isodaservice >(); , instead dependencies should automatically injected when run program
class program { public static isodaservice s { get; set; } static void main(string[] args) { setupcontainer(); //s = container.resolve<isodaservice>(); console.write(s.getsoda()); console.read(); } private static void setupcontainer() { var builder = new containerbuilder(); builder.registertype<soda>().as<isoda>(); builder.registertype<sodaservice>().as<isodaservice>().propertiesautowired(); builder.build(); } }
the problem have main method static. instanciate class of program , use non static class
class program { public isodaservice s { get; set; } static void main(string[] args) { var resolver=setupcontainer(); var instance=resolver.resolve<program>(); instance.execute(args); } public void execute(string[] args) { console.write(s.getsoda()); console.read(); } private autofac.icontainer void setupcontainer() { var builder = new containerbuilder(); builder.registertype<soda>().as<isoda>(); builder.registertype<sodaservice>().as<isodaservice>().propertiesautowired(); builder.registertype<program>().propertiesautowired(); return builder.build(); } }
Comments
Post a Comment