C# Interface, Unity, and Optional Parameter -
hopefully can shed light on one. have interface optional parameter. use unity. if try change optional parameter in method implementation, works directly, unity object uses interface's default - not implemented method's default.
setup:
public interface itestoptional { string happymethod(string input, bool amhappy = false); } public class testingoptional : itestoptional { public string happymethod(string input, bool amhappy = true) { if (amhappy) return input + " happy!"; return input + " not happy!"; } }
add unity:
container.registertype<itestoptional, testingoptional>();
and test:
//direct call var testdirect = new testingoptional(); string happydirect = testdirect.happymethod("cow", true); //expecting happy - happy string saddirect = testdirect.happymethod("cow", false); //expecting not happy - not happy string defaultdirect = testdirect.happymethod("cow"); //expecting happy (default) happy //unity var testunity = servicelocator.current.getinstance<itestoptional>(); string happyunity = testunity.happymethod("cow", true); //expecting happy - happy string sadunity = testunity.happymethod("cow", false); //expecting not happy - not happy string defaultunity = testunity.happymethod("cow"); //expecting happy (default) not happy.
any ideas why unity object uses false optional parameter when implementation uses true?
servicelocator.current.getinstance<itestoptional>();
returns compile type itestoptional
, call testunity.happymethod("cow");
converted compiler use default value specified in interface.
similarly new testingoptional();
returns compile time testingoptional
, compiler pick default class.
possible solution (short of adjusting expectations/not using different defaults): can resolve type directly using unity instead of resolving interfce (sometimes useful tests):
var directviacontainer = container.resolve<testingoptional>();
side note: re-defining default values in class implementing interface not god practice - you'll confusing code often.
Comments
Post a Comment