Dependency for static method

I have a class in the API, there is a static method designed to check and register details. Any guidance on how to introduce an ILogger interface, please.

public class ValidateDataInAPI
{
    public static bool IsValid(string data)
    {
        //do something
        If(error) 
        {
            _logger.Error("Log error as implemented by caller");
        }
    }
}
+4
source share
1 answer

If I understand correctly, you want to inject an instance of ILogger into a static method. As you probably already figured out, you cannot use the Dependency Injection "normal way" when the dependent method is static.

Here you can find the service locator pattern .

Using the StructureMap IoC container (but you can really use any container), the configuration for connecting it might look like this:

For<ILogger>().Use<SomeLoggerImplementation>();

:

public class ValidateDataInAPI
{
    private static ILogger Logger
    {
        // DependencyResolver could be any DI container here.
        get { return DependencyResolver.Resolve<ILogger>(); }
    }

    public static bool IsValid(string data)
    {
        //do something
        If(error) 
        {
            Logger.Error("Log error as implemented by caller");
        }
    }
}

, -, , , - .

Injection Dependency , , .

( "" ), . IoC Unit Tests, ? Dependency Injection , unit test .

Injection Dependency, . .

:

public class ValidateDataInAPI : IValidateDataInAPI
{
    private readonly ILogger _logger;

    // Since the dependency on ILogger is now exposed through the class constructor
    // you can easily create a unit test for this class and inject a mock of ILogger.
    // You will not need to configure your DI container to be able to unit test.
    public ValidateDataInAPI(ILogger logger)
    {
        _logger = logger;
    }

    public bool IsValid(string data)
    {
        //do something
        If(error) 
        {
            _logger.Error("Log error as implemented by caller");
        }
    }
}

, , , API:

public interface IValidateDataInAPI
{
    bool IsValid(string data);
}

Validator, unit test API .

, , IsValid , , , .

+5

All Articles