c# - Instantiate interface when null -
i working interfaces first time create loosely coupled code. in 1 of classes have following constructor:
public exceptionhandler(string loglocation = null, icanlocalize localizer = null)
the localizer in constructor optional , null default (since not wants localize class). right have class localizer
implements interface. class has constructor parameters full functionality , constructor without parameters basic null checking. mean both constructors set bool indicates if class initialized. in case it's not (empty constructor) default values returned without localizing them.
so in code can have
_localizer.getstring("key", "optional fallback value");
in case it's initialized return 'key' in english or 'sleutel' in dutch. if not initialized, 'optional fallback value' returned (or key
if no fallback value set). in order achieve behavior following in constructor of exceptionhandler
:
_localizer = localizer ?? new localizer();
this tightly couples classes again not intended. discovered i'd done after refactoring localizer
class have intended behavior.
now, 1 of solutions though of add localizer.createlocalizer()
interface uses empty constructor in localizer
class. unfortunately has no use since exception thrown because localizer
null. other approach tried add static method interface failed because interfaces can't have statics.
right i'm clueless how can tackle problem. option check in exceptionhandler
if localizer
null , anticipate inside class or there solution didn't think of yet? factories, these have use here , how effect coupling of code?
in humble opinion, shouldn't re-invent square wheel use existing wheel. you're trying called dependency injection. , should learn inversion of control too.
what using framework castle windsor?
windsorcontainer container = new windsorcontainer(); container.register(component.for<iexceptionhandler>().implementedby<exceptionhandler>()); container.register(component.for<ilocalizer>().implementedby<localizer>()); iexceptionhandler handler = container.resolve<iexceptionhandler>(); // if there's constructor registered component inject // automatically, if set injected ilocalizer public property // of iexceptionhandler implementation constructor, you'll defined // implementation localizer! handler = container.localizer;
there're many options out there. example ninject.
Comments
Post a Comment