Al2110
Al2110

Reputation: 576

Injecting a dependency that is a static variable in a class

A WinForms application uses the following "configuration class" (partial code):

public class Configuration
{
    public static Project currentProject;
}

Many other classes in the application currently use this Project variable, for example:

public class Controller
{
    public void processSomething()
    {
        Configuration.currentProject.doSomething();
    }
}

For the purposes of loose coupling, I want to be able to inject a Project variable as a dependency. The problem is, the Configuration.currentProject value might change at runtime. How should this be dealt with? Can passing it by reference solve it?

Upvotes: 0

Views: 852

Answers (1)

mjwills
mjwills

Reputation: 23820

I'd suggest passing in a Func<IProject> or Func<Project>. This will allow you to nicely handle changes to Configuration.currentProject (since invoking the function will always see the current value of the static) and also allow relatively easy writing of unit tests.

That being said, I'd strongly encourage you to move away from use of static and manual dependency injection. If you used a IoC container (e.g. Autofac) then Func and singleton support (without static) will likely be built in.

Upvotes: 2

Related Questions