Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Saturday, January 8, 2022

WinForms Dependency Injection in .NET6

This entry is motivated by the discussion in one of StackOverflow's questions, the How to use dependency injection in WinForms. A correct answer by Reza Aghaei shows how the container can be created and used, however, one of drawbacks of Reza's answer is that the container is used directly, which makes this approach fall under the Service Locator antipattern.
I've decided then to create a follow up and show one of possible correct solutions. This solution is based on the Local Factory pattern.
We'll start with a form factory
public interface IFormFactory
{
	Form1 CreateForm1();
	Form2 CreateForm2();
}

public class FormFactory : IFormFactory
{
	static IFormFactory _provider;

	public static void SetProvider( IFormFactory provider )
	{
		_provider = provider;
	}

	public Form1 CreateForm1()
	{
		return _provider.CreateForm1();
	}

	public Form2 CreateForm2()
	{
		return _provider.CreateForm2();
	}
}
From now on, this factory is the primary client's interface to creating forms. The client code is no longer supposed to just call
var form1 = new Form1();
No, it's forbidden. Instead, the client should always call
var form1 = new FormFactory().CreateForm1();
(and similarily for other forms).
Note that while the factory is implemented, it doesn't do anything on its own! Instead it delegates the creation to a somehow mysterious provider which has to be injected into the factory. The idea behind this is that the provider will be injected, once, in the Composition Root which is a place in the code, close to the startup, and very high in the application stack so that all dependencies can be resolved there. So, the form factory doesn't need to know what provider will be ultimately injected into it.
This approach has a significant advantage - depending on actual requirements, different providers can be injected, for example you could have a DI-based provider (we'll write it in a moment) for an actual application and a stub provider for unit tests.
Anyway, let's have a form with a dependency:
public partial class Form1 : Form
{
	private IHelloWorldService _service;

	public Form1(IHelloWorldService service)
	{
		InitializeComponent();

		this._service = service;
	}
}
This form depends on a service and the service will be provided by the constructor. If the Form1 needs to create another form, Form2, it does it it a way we already discussed:
var form2 = new FormFactory().CreateForm2();
Things become more complicated, though, when a form needs not only dependant services but also, just some free parameters (strings, ints etc.). Normally, you'd have a constructor
public Form2( string something, int somethingElse ) ...
but now you need something more like
public Form2( ISomeService service1, IAnotherService service2, string something, int somethingElse ) ...
This is something we should really take a look into. Look once again, a real-life form possibly needs
  1. some parameters that are resolved by the container
  2. other parameters that should be provided by the form creator (not known by the container!).
How do we handle that?
To have a complete example, let's then modify the form factory
public interface IFormFactory
{
	Form1 CreateForm1();
	Form2 CreateForm2(string something);
}

public class FormFactory : IFormFactory
{
	static IFormFactory _provider;

	public static void SetProvider( IFormFactory provider )
	{
		_provider = provider;
	}

	public Form1 CreateForm1()
	{
		return _provider.CreateForm1();
	}

	public Form2 CreateForm2(string something)
	{
		return _provider.CreateForm2(something);
	}
}
And let's see how forms are defined
public partial class Form1 : Form
{
	private IHelloWorldService _service;

	public Form1(IHelloWorldService service)
	{
		InitializeComponent();

		this._service = service;
	}

	private void button1_Click( object sender, EventArgs e )
	{
		var form2 = new FormFactory().CreateForm2("foo");
		form2.Show();
	}
}

public partial class Form2 : Form
{
	private IHelloWorldService _service;
	private string _something;

	public Form2(IHelloWorldService service, string something)
	{
		InitializeComponent();

		this._service = service;
		this._something = something;

		this.Text = something;
	}
}
Can you see a pattern here?
  1. whenever a form (e.g. Form1) needs only dependand services, it's creation method in the FormFactory is empty (dependencies will be resolved by the container).
  2. whenever a form (e.g. Form2) needs dependand services and other free parameters, it's creation method in the FormFactory contains a list of arguments corresponding to these free parameters (service dependencies will be resolved by the container)
Now finally to the Composition Root. Let's start with the service
public interface IHelloWorldService
{
	string DoWork();
}

public class HelloWorldServiceImpl : IHelloWorldService
{
	public string DoWork()
	{
		return "hello world service::do work";
	}
}
Note that while the interface is supposed to be somewhere down in the stack (to be recognized by everyone), the implementation is free to be provided anywhere (forms don't need reference to the implementation!). Then, follows the starting code where the form factory is finally provided and the container is set up
internal static class Program
{
	[STAThread]
	static void Main()
	{
		var formFactory = CompositionRoot();

		ApplicationConfiguration.Initialize();
		Application.Run(formFactory.CreateForm1());
	}

	static IHostBuilder CreateHostBuilder()
	{
		return Host.CreateDefaultBuilder()
			.ConfigureServices((context, services) => {
				services.AddTransient<IHelloWorldService, HelloWorldServiceImpl>();
				services.AddTransient<Form1>();
				services.AddTransient<Func<string,Form2>>(
					container =>
						something =>
						{
							var helloWorldService = 
                                container.GetRequiredService<IHelloWorldService>();
							return new Form2(helloWorldService, something);
						});
			});
	}

	static IFormFactory CompositionRoot()
	{
		// host
		var hostBuilder = CreateHostBuilder();
		var host = hostBuilder.Build();

		// container
		var serviceProvider = host.Services;

		// form factory
		var formFactory = new FormFactoryImpl(serviceProvider);
		FormFactory.SetProvider(formFactory);

		return formFactory;
	}
}

public class FormFactoryImpl : IFormFactory
{
	private IServiceProvider _serviceProvider;

	public FormFactoryImpl(IServiceProvider serviceProvider)
	{
		this._serviceProvider = serviceProvider;
	}

	public Form1 CreateForm1()
	{
		return _serviceProvider.GetRequiredService<Form1>();
	}

	public Form2 CreateForm2(string something)
	{
		var _form2Factory = _serviceProvider.GetRequiredService<Func<string, Form2>>();
		return _form2Factory( something );
	}
}
First note how the container is created with Host.CreateDefaultBuilder, an easy task. Then note how services are registered and how forms are registered among other services.
This is straightforward for forms that don't have any dependencies, it's just
services.AddTransient<Form1>();
However, if a form needs both services and free parameters, it's registered as ... form creation function, a Func of any free parameters that returns actual form. Take a look at this
services.AddTransient<Func<string,Form2>>(
	container =>
		something =>
		{
			var helloWorldService = container.GetRequiredService<IHelloWorldService>();
			return new Form2(helloWorldService, something);
		});
That's clever. We register a form factory function using one of registration mechanisms that itself uses a factory function (yes, a factory that uses another factory, a Factception. Feel free to take a short break if you feel lost here). Our registered function, the Func<string, Form2> has a single parameter, the something (that corresponds to the free parameter of the form constructor) but its other dependencies are resolved ... by the container (which is what we wanted).
This is why the actual form factory needs to pay attention of what it resolves. A simple form is resolved as follows
return _serviceProvider.GetRequiredService<Form1>();
where the other is resolved in two steps. We first resolve the factory function and then use the creation's method parameter to feed it to the function:
var _form2Factory = _serviceProvider.GetRequiredService<Func<string, Form2>>();
return _form2Factory( something );
And, that's it. Whenever a form is created, is either
new FormFactory().CreateForm1();
for "simple" forms (with service dependencies only) or just
new FormFactory().CreateForm2("foo");
for forms that need both service dependncies and other free parameters.
Happy coding. A simple excercise for you is to provide a different form factory, a factory that doesn't use a container but composes dependencies directly, for example for unit tests.

Monday, December 10, 2012

DI, Factories and the Composition Root

Make sure to read a follow-up version of this article.

This tutorial assumes you know what DI/IoC is but you are still unsure how to use it in complex scenarios.

Let me start with a common issue. Somewhere deep in your solution, in an assembly, there is a business service:

public interface IBusinessSerivce 
{
    void DoSomeWork();
}

Then, possibly in yet another assembly you have a class which uses the service:

public class SomeAnotherClass
{
    public void DoThat()
    {
        IBusinessSerivce service = ???
    }
}

How are you supposed to satisfy the dependency here?

There are at least few possible approaches here. Assuming you don’t want a concrete class to be instantiated here, you are left with three possibilities. Let us discuss them one by one.

First possibility – would be to use a service locator. A service locator acts just like a powerful magician – it can show up anywhere in your code and create any service you want (assuming it was registered in the IoC container):

public class SomeAnotherClass
{
    public void DoThat()
    {
        IBusinessSerivce service = 
            ServiceLocator.Current.GetInstance<IBusinessSerivce>();
    }
}

Yep, a kind of magic indeed. No additional dependencies, clean code.

But … is it really? Well, there is one additional dependency! To be able to use the locator, you had to make your project dependant on the locator implementation!

Is this wrong? Possibly. The class library is no longer self-contained. If you distribute it in a binary form, you have to include all the stuff which comes with the locator, one (or more) additional libraries.

Yet another reason a locator is bad is that although the dependency exists (SomeAnotherClass depends on IBusinessService), it is so implicit, so intimate, that any client of SomeAnotherClass would not be aware of the dependency. It’s just, “ok, let me use the class and … boom! I got an exception in runtime because the locator was not able to resolve the service and this was because the implementation had not been registered in the container but how the hell I was supposed to know that the class requires the service implementation to be registered? By studying the implementation?”

This is why the Service Locator is currently considered an anti-pattern.

Another possibility – but let just introduce it for the sake of completeness – would be to actually introduce an explicit dependency to … the container:

public class SomeAnotherClass
{
    private IUnityContainer container { get; set; }
 
    public SomeAnotherClass( IUnityContainer container )
    {
        this.container = container;
    }
 
    public void DoThat()
    {
        IBusinessSerivce service = 
            container.Resolve<IBusinessSerivce>();
    }
}

Well, at least one problem goes away – this time the dependency is explicit and the client of SomeAnotherClass must satisfy it in an explicit way. The other problem remains however, the dependency to the IoC container infrastructure. It just doesn’t look good. Surprisingly, I sometimes see people coding like this.

An ultimate possibility – because SomeAnotherClass depends on the service, let’s make this dependency explicit:

public class SomeAnotherClass
{
    private IBusinessSerivce service { get; set; }
 
    public SomeAnotherClass( IBusinessSerivce service )
    {
        this.service = service;
    }
 
    public void DoThat()
    {
        IBusinessSerivce service = this.service;
    }
}

Great, the dependency is explicit and the other dependency – to the IoC infrastructure is gone. And although this approach can possibly lead to other issues (namely the “constructor over-injection antipattern”) these can possibly be resolved somehow or somehow else.

Problem solved.

Is it, really?

Unfortunately, no. This is where the problem starts! By making the dependency explicit, we just throw the issue away. But it just hits someone else, directly in the face. Because now the client of SomeAnotherClass has exactly the same problem!

public class SomeClass
{
    public void DoThis()
    {
        SomeAnotherClass another = new SomeAnotherClass( ??? );
        another.DoThat();
    }
}

Well, to satisfy the dependency between SomeAnotherClass and IBusinessService I need an instance of the latter. And how do I resolve it?

Well, there are three possibilities, we’ve just discussed them :) And we concluded that the best we could do is to make the dependency explicit:

public class SomeClass
{
    private IBusinessSerivce service { get; set; }
 
    public SomeClass( IBusinessSerivce service )
    {
        this.service = service;
    }
 
    public void DoThis()
    {
        SomeAnotherClass another = new SomeAnotherClass( this.service );
        another.DoThat();
    }
}

This doesn’t look good, unfortunately and this is the core of the problem. By having multiple services in your system and multiple dependencies between various classes, this approach would end up in an object graph where each class depends on all possible services because possibly one of its dependant classes (or the class two, three or more nodes away in the dependency graph) depends on it!

Can you see it? You just can’t rethrow the responsibility to satisfy class dependencies to the client of the class because the client has its clients and they have their clients, too. The sole point of writing this entry is to show how to stop this madness of endless explicit dependencies which would flood your system.

But let us recap facts.

1. SomeAnotherClass really depends on the service because it makes use of it (DoThat method).

2. SomeClass doesn’t really depend on the service, it just depends on SomeAnotherClass. And to resolve the dependency, the SomeClass must somehow create an instance of the service.

3. Most probably we still want the IoC container to register/resolve the concrete implementation of the service but in the same time we don’t want SomeClass to depend on the service locator and/or the container in an explicit way.

And to cope with the issue we are going to introduce a factory. The factory will let its clients to create instances of the service. But we don’t want a concrete factory as it would end up with one, specific way of providing instances. Instead, we want the factory to be parametrized. We want a concrete implementation of the factory to be provided for the system.

For this to work, we will need a conrete class, a factory provider, which will be responsible for registering and providing a concrete implementation of the factory.

public interface IBusinessServiceFactory
{
    IBusinessSerivce CreateService();
}
 
public class BusinessServiceFactoryProvider
{
    public static IBusinessServiceFactory Factory { get; private set; }
 
    /// <summary>
    /// To be called in the Composition Root
    /// </summary>
    public static void SetupFactory( IBusinessServiceFactory factory )
    {
        Factory = factory;
    }
}

Now I can go back to my SomeClass, the one which has to satisfy the dependency to the service but is not itself dependant on the service:

public class SomeClass
{
    public SomeClass()
    {
    }
 
    public void DoThis()
    {
        var factory = BusinessServiceFactoryProvider.Factory;
 
        SomeAnotherClass another = new SomeAnotherClass( factory.CreateService() );
        another.DoThat();
    }
}

(#side note for purists who do not like static properties: the factory provider can be implemented to hide the lifetime of the factory:

public class BusinessServiceFactoryProvider
{
    private static IBusinessServiceFactory _factory { get; private set; }
 
    public IBusinessServiceFactory Factory
    {
        get
        {
            return _factory;
        }
    }
 
    /// <summary>
    /// To be called in the Composition Root
    /// </summary>
    /// <param name="factory"></param>
    public static void SetupFactory( IBusinessServiceFactory factory )
    {
        _factory = factory;
    }
}

so that the client code now becomes

public class SomeClass
 {
     public SomeClass()
     {
     }
 
     public void DoThis()
     {
         var factoryProvider = new BusinessServiceFactoryProvider();
         var factory = factoryProvider.Factory;
 
         SomeAnotherClass another = new SomeAnotherClass( factory.CreateService() );
         another.DoThat();
     }
 }

or even

public class BusinessServiceFactoryProvider
{
    private static IBusinessServiceFactory _factory { get; private set; }
 
    public IBusinessServiceFactory Factory
    {
        get
        {
            return _factory;
        }
    }
 
    /// <summary>
    /// To be called in the Composition Root
    /// </summary>
    /// <param name="factory"></param>
    public static void SetupFactory( 
       Func<IBusinessServiceFactory> factoryCreationMethod )
    {
        _factory = factoryCreationMethod();
    }
}

which makes it possible to implement arbitrary lifetime policy of the factory

#end of side note)

The factory provider really solves the issue once for all. I can provide a concrete implementation of the factory by making the configuration of the factory provider a part of the Composition Root:

class Program
{
    static void Main( string[] args )
    {
        ConfigureContainer();
 
        SomeClass sc = new SomeClass();
        sc.DoThis();
 
        Console.ReadLine();
    }
 
    static void ConfigureContainer()
    {
        IUnityContainer container = new UnityContainer();
 
        // register the service implementation
        container.RegisterType<IBusinessSerivce, BusinessServiceImpl>();
 
        // configure the factory provider
        BusinessServiceFactoryProvider.SetupFactory( 
          () => 
             new ContainerBusinessServiceFactory( container ) );
    }
 
}
 
class ContainerBusinessServiceFactory : IBusinessServiceFactory
{
    #region IBusinessServiceFactory Members
 
    private IUnityContainer container { get; set; }
 
    public ContainerBusinessServiceFactory( IUnityContainer container )
    {
        this.container = container;
    }
 
    public IBusinessSerivce CreateService()
    {
        return container.Resolve<IBusinessSerivce>();
    }
 
    #endregion
}

Note that the ContainerBusinessServiceFactory is just a concrete implementation of the service factory and although it strongly depends on the container infrastructure, it does not really matter as the class is now a part of the Composition Root – it is defined close to the Main method which plays the role of the CR. In the same time the concrete implementation of the service factory class is not really important to its clients as they access the factory by using the provider. The key features of such approach are:

1. All the clients of the service do not depend on the container infrastructure, instead they depend on the factory provider

2. A concrete implementation of the factory can (and possibly should) depend on the container but since it is a part of the composition root, it frees other classes from being dependant on the container infrastructure

3. The intention of the factory provider is now clean and it is safe to make it a required part of the CR. I could even provide a default implementation of the factory which by convention uses the container to resolve service (because most probably this is what I’d really want to do) so that no configuration of the factory provider is necessary at all in the Composition Root. This would introduce a possible issue however – because now a default service provider would depend on the container infrastructure (so that we are back in the situation where the service library has to be distributed together with container libraries).

4. I can freely change the implementation of the factory provider so that the code uses another, more sophisticated conrete factory but this does not influence any client code at all

Happy coding.