c# - Dependency injection for a static method -
i have class in api, have static method, intended validate , log details. guidance how inject ilogger interface please.
public class validatedatainapi { public static bool isvalid(string data) { //do if(error) { _logger.error("log error implemented caller"); } } }
if understand correctly, want inject instance of ilogger static method. figured out cannot make use of dependency injection "normal way" when dependent method static.
what might looking here service locator pattern.
using structuremap ioc container (but can use container), configuration wiring might this:
for<ilogger>().use<someloggerimplementation>();
when implemented, calling code might this:
public class validatedatainapi { private static ilogger logger { // dependencyresolver di container here. { return dependencyresolver.resolve<ilogger>(); } } public static bool isvalid(string data) { //do if(error) { logger.error("log error implemented caller"); } } }
i point out can considered anti-pattern , should used when there clear justification, not out of convenience.
the whole idea of dependency injection inject dependencies calling code's constructor, thereby exposing of class's dependencies outside world.
this not improves readability of code (there no internally hidden "surprises"), improves testability. don't want configuring ioc container in unit tests projects, you? using dependency injection right way eliminates necessity , makes life whole lot easier when want unit test code.
if not familiar concept of dependency injection, this link started. there plenty of information out there.
with dependency injection calling code this:
public class validatedatainapi : ivalidatedatainapi { private readonly ilogger _logger; // since dependency on ilogger exposed through class's constructor // can create unit test class , inject mock of ilogger. // not need configure di container able unit test. public validatedatainapi(ilogger logger) { _logger = logger; } public bool isvalid(string data) { //do if(error) { _logger.error("log error implemented caller"); } } }
similarly, having interface defined validation class can inject validation class api class:
public interface ivalidatedatainapi { bool isvalid(string data); }
you can mock validator class allow unit test api class more easily.
having said that, if need keep isvalid method static, service locator pattern way go.
Comments
Post a Comment