-
Notifications
You must be signed in to change notification settings - Fork 222
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add readme "How To Implement Dependency Injection with Pure.DI code generator" #541
base: main
Are you sure you want to change the base?
Changes from 4 commits
39dfa58
e946bcc
c148850
5ffc50a
bf3b453
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,207 @@ | ||
--- | ||
id: how-to-implement-dependency-injection-with-pure-di | ||
title: How To Implement Dependency Injection with Pure.DI code generator | ||
--- | ||
|
||
# How To Implement Dependency Injection in Avalonia with Pure.DI code generator | ||
|
||
This example is based on [another example](how-to-implement-dependency-injection.md) on dependency injection showing the benefits of the pure Dependency Injection approach using the Pure.DI source code generator. | ||
|
||
## Step 0: Presentation model | ||
|
||
Compared to [this example](how-to-implement-dependency-injection.md), only a few properties and methods have been added to demonstrate real-world usage scenarios: | ||
|
||
```csharp | ||
public interface IMainViewModel | ||
{ | ||
string Title { get; } | ||
|
||
string Greetings { get; } | ||
} | ||
|
||
public class MainViewModel(IBusinessService businessService) | ||
: IMainViewModel | ||
{ | ||
public string Title => "Avalonia application"; | ||
|
||
public string Greetings => businessService.CreateGreetings(); | ||
} | ||
|
||
public interface IBusinessService | ||
{ | ||
string CreateGreetings(); | ||
} | ||
|
||
public class BusinessService(IRepository repository) | ||
: IBusinessService | ||
{ | ||
public string CreateGreetings() | ||
{ | ||
repository.RegisterSomething(); | ||
return "Example of Dependency Injection implementation using Pure.DI"; | ||
} | ||
} | ||
|
||
public interface IRepository | ||
{ | ||
void RegisterSomething(); | ||
} | ||
|
||
public class Repository: IRepository | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fix the formatting on this line There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done |
||
{ | ||
public void RegisterSomething() | ||
{ | ||
} | ||
} | ||
``` | ||
|
||
## Step 1: Install the NuGet package for DI | ||
|
||
Run the following command in a terminal inside your project directory to install the [Pure.DI](https://www.nuget.org/packages/Pure.DI) source generator package. | ||
|
||
```shell | ||
dotnet add package Pure.DI | ||
``` | ||
|
||
## Step 2: Add a composition class | ||
|
||
This class setups how the composition of objects will be created for the application. | ||
|
||
```csharp | ||
using Pure.DI; | ||
using static Pure.DI.Lifetime; | ||
|
||
public partial class Composition | ||
{ | ||
private static void Setup() => DI.Setup() | ||
.Root<MainWindow>(nameof(MainWindow)) | ||
.Root<IMainViewModel>(nameof(MainViewModel)) | ||
|
||
.Bind().As(Singleton).To<Repository>() | ||
.Bind().To<BusinessService>() | ||
.Bind().As(Singleton).To<MainViewModel>(); | ||
} | ||
``` | ||
|
||
Advantages over classical DI container libraries: | ||
- No performance impact or side effects when creating composition of objects. | ||
- All logic for analyzing the graph of objects, constructors and methods takes place at compile time. Pure.DI notifies the developer at compile time of missing or cyclic dependencies, cases when some dependencies are not suitable for injection, etc. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This paragraph is just an elaborated version of the previous one There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
This is a paragraph about the general benefits.
This paragraph describes the advantages of using Pure.DI in Avalonia applications. I have not combined them as they refer to different parts of the document. |
||
- Does not add dependencies to any additional assembly. | ||
- Since the generated code uses primitive language constructs to create object compositions and does not use any libraries, you can easily debug the object composition code as regular code in your application. | ||
|
||
## Step 3: Modify App.axaml.cs | ||
|
||
Next, the `App.xaml.cs` class should be modified to use the main window created in pure DI paradigm: | ||
|
||
```csharp | ||
public class App : Application | ||
{ | ||
public override void Initialize() | ||
{ | ||
AvaloniaXamlLoader.Load(this); | ||
} | ||
|
||
public override void OnFrameworkInitializationCompleted() | ||
{ | ||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop | ||
&& Resources[nameof(Composition)] is Composition composition) | ||
{ | ||
desktop.MainWindow = composition.MainWindow; | ||
} | ||
|
||
base.OnFrameworkInitializationCompleted(); | ||
} | ||
} | ||
``` | ||
|
||
This code is only needed to create a main window in a pure DI paradigm using a shared composition instance: | ||
|
||
```csharp | ||
if (Resources[nameof(Composition)] is Composition composition) | ||
{ | ||
desktop.MainWindow = composition.MainWindow; | ||
} | ||
``` | ||
|
||
This will be useful if the main window will require dependencies to be injected. | ||
|
||
Advantages over classical DI container libraries: | ||
- No explicit initialisation of data contexts is required. Data contexts are configured directly in `.axaml` files according to the MVVM approach. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I am not clear how what you have done is any different from the MS DI example. You are still explicitly resolving things from the container, just with more steps. This also sounds like you are implying the MS DI approach violates MVVM somehow? There is also really nothing stopping you from setting up MS DI in a similar way. It just requires slightly more effort (and also a static locator). There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Pure.DI doesn't create a container like in classic DI container frameworks. Pure.DI is a source code generator. For the example in this document, it generates a class like this: AvaloniaSimpleApp namespace;
partial class Composition
{
private readonly Lock _lock = new();
private MainViewModel? _mainViewModel;
private Repository? _repository;
public IMainViewModel MainViewModel
{
get
{
if (_mainViewModel is null)
{
using (_lock.EnterScope())
{
if (_mainViewModel is null)
{
if (_repository is null)
{
_repository = new Repository();
}
_mainViewModel = new MainViewModel(new BusinessService(_repository));
}
}
}
return _mainViewModel;
}
}
public MainWindow MainWindow => new()
} This class is roughly what you would write if you were doing object composition in a pure DI paradigm by hand. There aren't any dependencies on third party libraries, you don't need methods like How many more steps are you talking about? All you need to do is to define one instance of the class in the resources to create the roots of the composition, and that's it. Except for the settings themselves for defining the dependency graph, there is no more code, everything is customized by bindings inside xaml files. Just count the number of lines of code in the examples.
I suggest you try doing this for MS DI, I'm not sure it will look as easy, at least not because any classic DI library has a Service Locator at the very beginning. I'm not claiming that the MS DI approach somehow violates MVVM, I'm just pointing out that the presentation layer in the Pure.DI approach is even more clearly separated from the other layers and is consistent with MVVM. The presentation layer has no .cs files and no tricks to initialize data contexts. |
||
- The code is simpler, more compact, and requires less maintenance effort. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is fairly opinionated, which I would argue does not belong in a tutorial like this. You should present facts and let people make their own decision There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Totally agree, fixed |
||
- The main window is created in a pure DI paradigm, and it can be easily supplied with all necessary dependencies via DI as regular types. | ||
|
||
## Step 4: Modify App.axaml | ||
|
||
Next, modify the `App.axaml` file to use view models according to the MVVM approach via a shared resource: | ||
|
||
```xml | ||
<Application xmlns="https://github.com/avaloniaui" | ||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" | ||
xmlns:app="clr-namespace:AvaloniaSimpleApp" | ||
x:Class="AvaloniaSimpleApp.App" | ||
RequestedThemeVariant="Default"> | ||
|
||
<!-- "Default" ThemeVariant follows system theme variant. | ||
"Dark" or "Light" are other available options. --> | ||
<Application.Styles> | ||
<FluentTheme /> | ||
</Application.Styles> | ||
|
||
<Application.Resources> | ||
<app:Composition x:Key="Composition" /> | ||
</Application.Resources> | ||
|
||
</Application> | ||
``` | ||
|
||
This markup fragment | ||
|
||
```xml | ||
<Application.Resources> | ||
<app:Composition x:Key="Composition" /> | ||
</Application.Resources> | ||
``` | ||
|
||
creates a shared resource of type `Composition` and with key _‘Composition’_, which will be further used as a data context in the views. | ||
|
||
## Step 5: Create your views according to MVVM approach | ||
|
||
You can now use bindings to model views without even editing the views `.cs` code files, for example for the main window in the example this might look like this: | ||
|
||
```xml | ||
<Window xmlns="https://github.com/avaloniaui" | ||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" | ||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" | ||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" | ||
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" | ||
x:Class="AvaloniaSimpleApp.MainWindow" | ||
DataContext="{StaticResource Composition}" | ||
xmlns:app="clr-namespace:AvaloniaSimpleApp" | ||
x:DataType="app:Composition" | ||
Title="{Binding MainViewModel.Title}" | ||
Content="{Binding MainViewModel.Greetings}"/> | ||
``` | ||
|
||
To use bindings in views: | ||
|
||
- You can set a shared resource as a data context | ||
|
||
`DataContext="{StaticResource Composition}"` | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This may(?) cause side effects when running inside the previewer, as the previewer will run your real app code. You really should have a separate set of test services that sets the design time data context There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You are absolutely right, but this is absolutely true for other approaches as well. I didn't take the time to support DesignTime, for the simplicity of the example. But it is easily solved by an alternative class like |
||
|
||
The resource with key _"Composition"_ was defined in [step 4](#step-4-modify-appaxaml). | ||
|
||
- Specify the data type in the context: | ||
|
||
`xmlns:app="clr-namespace:AvaloniaSimpleApp"` | ||
|
||
`x:DataType="app:Composition"` | ||
|
||
- Use the bindings as usual: | ||
|
||
`Title="{Binding MainViewModel.Title}"` | ||
|
||
Advantages over classical DI container libraries: | ||
- The code-behind `.cs` files for views are free of any logic. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There are many ways to do DI without using a static locator or putting any DI logic on code behind that work in basically every DI framework. The original example code for MSDI mentioned one possible way, it was just removed due to the lack of practical examples in the guide. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't have much experience using Avalonia, but have had experience with WPF. The main way to work with classic DI containers is to use methods like I'm not sure I know of a way to use them in bindings without any tricks. In the link you suggested, as far as I understand we just provide access to the container via a static property. This approach does not reduce the dependency of the view layer compared to the current MS DI approach. |
||
- This approach works just as well during design time. | ||
- You can easily use different view models in a single view. | ||
- Bindings depend on properties through abstractions, which additionally ensures weak coupling of types in application. This is in line with the basic principles of DI. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Primary constructors are a fairly new feature. They should probably be avoided for now to ensure anybody copying and pasting the code can use it without worrying about their language version.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done