├── .github
└── workflows
│ ├── dotnet.yml
│ └── release.yml
├── .gitignore
├── LICENSE
├── README.md
└── src
├── AvaloniaSample
├── AppDefault.axaml
├── AppDefault.axaml.cs
├── AppEmpty.axaml
├── AppEmpty.axaml.cs
├── AppWithServiceProvider.axaml
├── AppWithServiceProvider.axaml.cs
├── Assets
│ └── avalonia-logo.ico
├── AvaloniaSample.csproj
├── Program.cs
├── Services
│ ├── ISomeService.cs
│ └── SomeService.cs
├── ViewLocator.cs
├── ViewModels
│ ├── MainWindowViewModel.cs
│ ├── MainWindowViewModelWithParams.cs
│ └── ViewModelBase.cs
├── Views
│ ├── MainWindow.axaml
│ └── MainWindow.axaml.cs
├── app.manifest
└── rd.xml
├── Lemon.Hosting.AvaloniauiDesktop.sln
├── Lemon.Hosting.AvaloniauiDesktop
├── AvaloniauiApplicationLifetime.cs
├── AvaloniauiApplicationLifetimeExtensions.cs
└── Lemon.Hosting.AvaloniauiDesktop.csproj
├── Package.props
└── lemon-100.png
/.github/workflows/dotnet.yml:
--------------------------------------------------------------------------------
1 | name: .NET
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | pull_request:
8 | branches:
9 | - main
10 |
11 | jobs:
12 | build:
13 | runs-on: ${{ matrix.os }}
14 | strategy:
15 | matrix:
16 | os: [windows-2022, ubuntu-latest, macos-latest]
17 | steps:
18 | - uses: actions/checkout@v3
19 | - name: Setup .NET 8
20 | uses: actions/setup-dotnet@v3
21 | with:
22 | dotnet-version: 8.0.x
23 | - name: Install dependencies
24 | run: dotnet restore
25 | working-directory: src/AvaloniaSample
26 | - name: Build
27 | run: dotnet build --configuration Release --no-restore
28 | working-directory: src/AvaloniaSample
29 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Pack Nuget
2 |
3 | on:
4 | push:
5 | branches: [ "action/release" ]
6 | pull_request:
7 | branches: [ "action/release" ]
8 |
9 | jobs:
10 | nuget:
11 | runs-on: ubuntu-latest
12 | steps:
13 | - name: Checkout
14 | uses: actions/checkout@v4.1.1
15 |
16 | - name: Build the Project
17 | run: dotnet build ./src/Lemon.Hosting.AvaloniauiDesktop --configuration Release
18 |
19 | - name: Pack Nuget
20 | run: dotnet pack ./src/Lemon.Hosting.AvaloniauiDesktop -o ./nugets
21 |
22 | - name: Publish NuGet package
23 | run: dotnet nuget push "./nugets/*.nupkg" --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate
24 |
25 | - name: Upload a Build Artifact
26 | uses: actions/upload-artifact@v4.3.1
27 | with:
28 | name: nugets
29 | path: ./nugets
30 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.tlog
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.)
298 | *.vbp
299 |
300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project)
301 | *.dsw
302 | *.dsp
303 |
304 | # Visual Studio 6 technical files
305 | *.ncb
306 | *.aps
307 |
308 | # Visual Studio LightSwitch build output
309 | **/*.HTMLClient/GeneratedArtifacts
310 | **/*.DesktopClient/GeneratedArtifacts
311 | **/*.DesktopClient/ModelManifest.xml
312 | **/*.Server/GeneratedArtifacts
313 | **/*.Server/ModelManifest.xml
314 | _Pvt_Extensions
315 |
316 | # Paket dependency manager
317 | .paket/paket.exe
318 | paket-files/
319 |
320 | # FAKE - F# Make
321 | .fake/
322 |
323 | # CodeRush personal settings
324 | .cr/personal
325 |
326 | # Python Tools for Visual Studio (PTVS)
327 | __pycache__/
328 | *.pyc
329 |
330 | # Cake - Uncomment if you are using it
331 | # tools/**
332 | # !tools/packages.config
333 |
334 | # Tabs Studio
335 | *.tss
336 |
337 | # Telerik's JustMock configuration file
338 | *.jmconfig
339 |
340 | # BizTalk build output
341 | *.btp.cs
342 | *.btm.cs
343 | *.odx.cs
344 | *.xsd.cs
345 |
346 | # OpenCover UI analysis results
347 | OpenCover/
348 |
349 | # Azure Stream Analytics local run output
350 | ASALocalRun/
351 |
352 | # MSBuild Binary and Structured Log
353 | *.binlog
354 |
355 | # NVidia Nsight GPU debugger configuration file
356 | *.nvuser
357 |
358 | # MFractors (Xamarin productivity tool) working folder
359 | .mfractor/
360 |
361 | # Local History for Visual Studio
362 | .localhistory/
363 |
364 | # Visual Studio History (VSHistory) files
365 | .vshistory/
366 |
367 | # BeatPulse healthcheck temp database
368 | healthchecksdb
369 |
370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
371 | MigrationBackup/
372 |
373 | # Ionide (cross platform F# VS Code tools) working folder
374 | .ionide/
375 |
376 | # Fody - auto-generated XML schema
377 | FodyWeavers.xsd
378 |
379 | # VS Code files for those working on multiple tools
380 | .vscode/*
381 | !.vscode/settings.json
382 | !.vscode/tasks.json
383 | !.vscode/launch.json
384 | !.vscode/extensions.json
385 | *.code-workspace
386 |
387 | # Local History for Visual Studio Code
388 | .history/
389 |
390 | # Windows Installer files from build outputs
391 | *.cab
392 | *.msi
393 | *.msix
394 | *.msm
395 | *.msp
396 |
397 | # JetBrains Rider
398 | .idea/
399 | *.sln.iml
400 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Easley wang
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | # Introduction
17 | .NET Generic Host support for Avaloniaui desktop app.
18 | Support Aot!
19 | - Examples:
20 | ```C#
21 | internal sealed class Program
22 | {
23 | [STAThread]
24 | [SupportedOSPlatform("windows")]
25 | [SupportedOSPlatform("linux")]
26 | [SupportedOSPlatform("macos")]
27 | [RequiresDynamicCode("Calls Microsoft.Extensions.Hosting.Host.CreateApplicationBuilder()")]
28 | public static void Main(string[] args)
29 | {
30 | var hostBuilder = Host.CreateApplicationBuilder();
31 |
32 | // config IConfiguration
33 | hostBuilder.Configuration
34 | .AddCommandLine(args)
35 | .AddEnvironmentVariables()
36 | .AddInMemoryCollection();
37 |
38 | // config ILogger
39 | hostBuilder.Services.AddLogging(builder => builder.AddConsole());
40 | // add some services
41 | hostBuilder.Services.AddSingleton();
42 |
43 | #region app default
44 | RunAppDefault(hostBuilder, args);
45 | #endregion
46 |
47 | #region app without mainwindow
48 | //RunAppWithoutMainWindow(hostBuilder, args);
49 | #endregion
50 |
51 | #region app with serviceprovider
52 | //RunAppWithServiceProvider(hostBuilder, args);
53 | #endregion
54 | }
55 |
56 | public static AppBuilder ConfigAvaloniaAppBuilder(AppBuilder appBuilder)
57 | {
58 | return appBuilder
59 | .UsePlatformDetect()
60 | .WithInterFont()
61 | .LogToTrace()
62 | .UseReactiveUI();
63 | }
64 |
65 | [SupportedOSPlatform("windows")]
66 | [SupportedOSPlatform("linux")]
67 | [SupportedOSPlatform("macos")]
68 | [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
69 | private static void RunAppDefault(HostApplicationBuilder hostBuilder, string[] args)
70 | {
71 | hostBuilder.Services.AddAvaloniauiDesktopApplication(ConfigAvaloniaAppBuilder);
72 | // build host
73 | var appHost = hostBuilder.Build();
74 | // run app
75 | appHost.RunAvaloniauiApplication(args);
76 | }
77 |
78 | [SupportedOSPlatform("windows")]
79 | [SupportedOSPlatform("linux")]
80 | [SupportedOSPlatform("macos")]
81 | [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
82 | private static void RunAppWithoutMainWindow(HostApplicationBuilder hostBuilder, string[] args)
83 | {
84 | // add avaloniaui application and config AppBuilder
85 | hostBuilder.Services.AddAvaloniauiDesktopApplication(ConfigAvaloniaAppBuilder);
86 | // add MainWindow & MainWindowViewModelWithParams
87 | hostBuilder.Services.AddMainWindow();
88 | // build host
89 | var appHost = hostBuilder.Build();
90 | // run app
91 | appHost.RunAvaloniauiApplication(args);
92 | }
93 |
94 | [SupportedOSPlatform("windows")]
95 | [SupportedOSPlatform("linux")]
96 | [SupportedOSPlatform("macos")]
97 | [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
98 | private static void RunAppWithServiceProvider(HostApplicationBuilder hostBuilder, string[] args)
99 | {
100 | // add avaloniaui application and config AppBuilder
101 | hostBuilder.Services.AddAvaloniauiDesktopApplication(ConfigAvaloniaAppBuilder);
102 | // add MainWindowViewModelWithParams
103 | hostBuilder.Services.AddSingleton();
104 | // build host
105 | var appHost = hostBuilder.Build();
106 | // run app
107 | appHost.RunAvaloniauiApplication(args);
108 | }
109 | }
110 | ```
111 |
112 | References:
113 | [Nito.Host.Wpf](https://github.com/StephenCleary/Hosting)
114 |
--------------------------------------------------------------------------------
/src/AvaloniaSample/AppDefault.axaml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/src/AvaloniaSample/AppDefault.axaml.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Controls.ApplicationLifetimes;
3 | using Avalonia.Markup.Xaml;
4 | using AvaloniaSample.ViewModels;
5 | using AvaloniaSample.Views;
6 |
7 | namespace AvaloniaSample;
8 |
9 | public partial class AppDefault : Application
10 | {
11 | public override void Initialize()
12 | {
13 | AvaloniaXamlLoader.Load(this);
14 | }
15 |
16 | public override void OnFrameworkInitializationCompleted()
17 | {
18 | if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
19 | {
20 | desktop.MainWindow = new MainWindow
21 | {
22 | DataContext = new MainWindowViewModel(),
23 | };
24 | }
25 | base.OnFrameworkInitializationCompleted();
26 | }
27 | }
--------------------------------------------------------------------------------
/src/AvaloniaSample/AppEmpty.axaml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/src/AvaloniaSample/AppEmpty.axaml.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Markup.Xaml;
3 |
4 | namespace AvaloniaSample;
5 |
6 | public partial class AppEmpty : Application
7 | {
8 | public override void Initialize()
9 | {
10 | AvaloniaXamlLoader.Load(this);
11 | }
12 | }
--------------------------------------------------------------------------------
/src/AvaloniaSample/AppWithServiceProvider.axaml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/src/AvaloniaSample/AppWithServiceProvider.axaml.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Controls.ApplicationLifetimes;
3 | using Avalonia.Markup.Xaml;
4 | using AvaloniaSample.ViewModels;
5 | using AvaloniaSample.Views;
6 | using Microsoft.Extensions.DependencyInjection;
7 | using System;
8 |
9 | namespace AvaloniaSample
10 | {
11 | public partial class AppWithServiceProvider : Application
12 | {
13 | private readonly IServiceProvider _serviceProvider;
14 | public AppWithServiceProvider(IServiceProvider serviceProvider):base()
15 | {
16 | _serviceProvider = serviceProvider;
17 | }
18 | public override void Initialize()
19 | {
20 | AvaloniaXamlLoader.Load(this);
21 | }
22 |
23 | public override void OnFrameworkInitializationCompleted()
24 | {
25 | if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
26 | {
27 | /// MainWindow and MainWindowViewModel have been added in hosting
28 | desktop.MainWindow = new MainWindow
29 | {
30 | //DataContext = new MainWindowViewModel(),
31 | DataContext = _serviceProvider.GetRequiredService()
32 | };
33 |
34 | /// ShutdownMode has been configured in hosting
35 | //desktop.ShutdownMode = Avalonia.Controls.ShutdownMode.OnMainWindowClose;
36 | }
37 | base.OnFrameworkInitializationCompleted();
38 | }
39 | }
40 | }
--------------------------------------------------------------------------------
/src/AvaloniaSample/Assets/avalonia-logo.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NeverMorewd/Hosting.Avaloniaui/9b96f69aaab9b1828e1fdf6afabb4f9c47718843/src/AvaloniaSample/Assets/avalonia-logo.ico
--------------------------------------------------------------------------------
/src/AvaloniaSample/AvaloniaSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | WinExe
4 | net8.0
5 | enable
6 | true
7 | app.manifest
8 | true
9 |
11 | 034dd32e-5d50-4863-8f08-45400331e3e3
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 | AppEmpty.axaml
41 |
42 |
43 | AppWithServiceProvider.axaml
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/src/AvaloniaSample/Program.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Controls;
3 | using Avalonia.Controls.ApplicationLifetimes;
4 | using Avalonia.ReactiveUI;
5 | using AvaloniaSample.Services;
6 | using AvaloniaSample.ViewModels;
7 | using AvaloniaSample.Views;
8 | using Lemon.Hosting.AvaloniauiDesktop;
9 | using Microsoft.Extensions.Configuration;
10 | using Microsoft.Extensions.DependencyInjection;
11 | using Microsoft.Extensions.Hosting;
12 | using Microsoft.Extensions.Logging;
13 | using System;
14 | using System.Runtime.CompilerServices;
15 | using System.Runtime.Versioning;
16 |
17 | namespace AvaloniaSample
18 | {
19 | internal sealed class Program
20 | {
21 | [STAThread]
22 | [SupportedOSPlatform("windows")]
23 | [SupportedOSPlatform("linux")]
24 | [SupportedOSPlatform("macos")]
25 | public static void Main(string[] args)
26 | {
27 | var hostBuilder = Host.CreateApplicationBuilder();
28 |
29 | // config IConfiguration
30 | hostBuilder.Configuration
31 | .AddCommandLine(args)
32 | .AddEnvironmentVariables()
33 | .AddInMemoryCollection();
34 |
35 | // config ILogger
36 | hostBuilder.Services.AddLogging(builder => builder.AddConsole());
37 | // add some services
38 | hostBuilder.Services.AddSingleton();
39 |
40 | #region run app default
41 | //RunAppDefault(hostBuilder, args);
42 | #endregion
43 |
44 | #region run empty app with mainwindow
45 | //RunAppWithMainWindow(hostBuilder, args);
46 | #endregion
47 |
48 | #region run app with serviceprovider
49 | //RunAppWithServiceProvider(hostBuilder, args);
50 | #endregion
51 |
52 | #region run app with serviceprovider
53 | //RunAppWithLifetime(hostBuilder, args);
54 | #endregion
55 |
56 | #region run app with serviceprovider
57 | RunAppWithLifetimePreSetupMainWindow(hostBuilder, args);
58 | #endregion
59 | }
60 |
61 | public static AppBuilder ConfigAvaloniaAppBuilder(AppBuilder appBuilder)
62 | {
63 | return appBuilder
64 | .UsePlatformDetect()
65 | .WithInterFont()
66 | .LogToTrace()
67 | .UseReactiveUI();
68 | }
69 |
70 | [SupportedOSPlatform("windows")]
71 | [SupportedOSPlatform("linux")]
72 | [SupportedOSPlatform("macos")]
73 | [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
74 | private static void RunAppDefault(HostApplicationBuilder hostBuilder, string[] args)
75 | {
76 | hostBuilder.Services.AddAvaloniauiDesktopApplication(ConfigAvaloniaAppBuilder);
77 | // build host
78 | var appHost = hostBuilder.Build();
79 | // run app
80 | appHost.RunAvaloniauiApplication(args);
81 | }
82 |
83 | [SupportedOSPlatform("windows")]
84 | [SupportedOSPlatform("linux")]
85 | [SupportedOSPlatform("macos")]
86 | [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
87 | private static void RunAppWithMainWindow(HostApplicationBuilder hostBuilder, string[] args)
88 | {
89 | // add avaloniaui application and config AppBuilder
90 | hostBuilder.Services.AddAvaloniauiDesktopApplication(ConfigAvaloniaAppBuilder);
91 | // add MainWindow & MainWindowViewModelWithParams
92 | hostBuilder.Services.AddMainWindow();
93 | // build host
94 | var appHost = hostBuilder.Build();
95 | // run app
96 | appHost.RunAvaloniauiApplication(args);
97 | }
98 |
99 | [SupportedOSPlatform("windows")]
100 | [SupportedOSPlatform("linux")]
101 | [SupportedOSPlatform("macos")]
102 | [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
103 | private static void RunAppWithServiceProvider(HostApplicationBuilder hostBuilder, string[] args)
104 | {
105 | // add avaloniaui application and config AppBuilder
106 | hostBuilder.Services.AddAvaloniauiDesktopApplication(ConfigAvaloniaAppBuilder);
107 | // add MainWindowViewModelWithParams
108 | hostBuilder.Services.AddSingleton();
109 | // build host
110 | var appHost = hostBuilder.Build();
111 | // run app
112 | appHost.RunAvaloniauiApplication(args);
113 | }
114 | [SupportedOSPlatform("windows")]
115 | [SupportedOSPlatform("linux")]
116 | [SupportedOSPlatform("macos")]
117 | [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
118 | private static void RunAppWithLifetime(HostApplicationBuilder hostBuilder, string[] args)
119 | {
120 |
121 | hostBuilder.Services.AddAvaloniauiDesktopApplication(ConfigAvaloniaAppBuilder);
122 | hostBuilder.Services.AddApplicationLifetime((sp) =>
123 | {
124 | var lifetime = new ClassicDesktopStyleApplicationLifetime
125 | {
126 | Args = args,
127 | ShutdownMode = ShutdownMode.OnMainWindowClose
128 | };
129 | return lifetime;
130 | });
131 | // build host
132 | var appHost = hostBuilder.Build();
133 | // run app
134 | appHost.RunAvaloniauiApplication(args);
135 | }
136 | [SupportedOSPlatform("windows")]
137 | [SupportedOSPlatform("linux")]
138 | [SupportedOSPlatform("macos")]
139 | [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
140 | private static void RunAppWithLifetimePreSetupMainWindow(HostApplicationBuilder hostBuilder, string[] args)
141 | {
142 | hostBuilder.Services.AddAvaloniauiDesktopApplication(ConfigAvaloniaAppBuilder);
143 | hostBuilder.Services.AddMainWindow();
144 | hostBuilder.Services.AddApplicationLifetime((sp) =>
145 | {
146 | var lifetime = new ClassicDesktopStyleApplicationLifetime
147 | {
148 | Args = args,
149 | ShutdownMode = ShutdownMode.OnMainWindowClose
150 | };
151 | return lifetime;
152 | });
153 | var appHost = hostBuilder.Build();
154 | appHost.RunAvaloniauiApplication(args);
155 | }
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/src/AvaloniaSample/Services/ISomeService.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace AvaloniaSample.Services
4 | {
5 | public interface ISomeService
6 | {
7 | int GetSomeNumber();
8 | IEnumerable> GetConfigurations();
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/AvaloniaSample/Services/SomeService.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.Configuration;
2 | using Microsoft.Extensions.Logging;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 |
7 | namespace AvaloniaSample.Services
8 | {
9 | public class SomeService : ISomeService
10 | {
11 | private readonly IServiceProvider _serviceProvider;
12 | private readonly IConfiguration _configuration;
13 | private readonly ILogger _logger;
14 | public SomeService(IServiceProvider serviceProvider,
15 | IConfiguration configuration,
16 | ILogger logger)
17 | {
18 | _serviceProvider = serviceProvider;
19 | _configuration = configuration;
20 | _logger = logger;
21 | }
22 |
23 | public IEnumerable> GetConfigurations()
24 | {
25 | _logger?.LogInformation("GetConfigurations");
26 | return _configuration.AsEnumerable();
27 | }
28 |
29 | public int GetSomeNumber()
30 | {
31 | return new Random().Next();
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/AvaloniaSample/ViewLocator.cs:
--------------------------------------------------------------------------------
1 | using Avalonia.Controls;
2 | using Avalonia.Controls.Templates;
3 | using AvaloniaSample.ViewModels;
4 | using System;
5 |
6 | namespace AvaloniaSample
7 | {
8 | public class ViewLocator : IDataTemplate
9 | {
10 | public Control? Build(object? data)
11 | {
12 | if (data is null)
13 | return null;
14 |
15 | var name = data.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
16 | var type = Type.GetType(name);
17 |
18 | if (type != null)
19 | {
20 | var control = (Control)Activator.CreateInstance(type)!;
21 | control.DataContext = data;
22 | return control;
23 | }
24 |
25 | return new TextBlock { Text = "Not Found: " + name };
26 | }
27 |
28 | public bool Match(object? data)
29 | {
30 | return data is ViewModelBase;
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/AvaloniaSample/ViewModels/MainWindowViewModel.cs:
--------------------------------------------------------------------------------
1 | using ReactiveUI;
2 |
3 | namespace AvaloniaSample.ViewModels
4 | {
5 | public class MainWindowViewModel:ViewModelBase
6 | {
7 |
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/src/AvaloniaSample/ViewModels/MainWindowViewModelWithParams.cs:
--------------------------------------------------------------------------------
1 | using AvaloniaSample.Services;
2 | using Microsoft.Extensions.Logging;
3 | using ReactiveUI;
4 | using System;
5 | using System.Reactive.Linq;
6 |
7 | namespace AvaloniaSample.ViewModels
8 | {
9 | public class MainWindowViewModelWithParams : ViewModelBase
10 | {
11 | private readonly ILogger _logger;
12 | private readonly ISomeService _someService;
13 | public MainWindowViewModelWithParams(ISomeService someService, ILogger logger)
14 | {
15 | _logger = logger;
16 | _someService = someService;
17 | Observable.Interval(TimeSpan.FromSeconds(1))
18 | .ObserveOn(RxApp.MainThreadScheduler)
19 | .Subscribe(_ =>
20 | {
21 | StringValue = $"Welcome to Lemon.Hosting.AvaloniauiDesktop:{_someService.GetSomeNumber()}";
22 | });
23 | }
24 |
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/AvaloniaSample/ViewModels/ViewModelBase.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Controls.ApplicationLifetimes;
3 | using ReactiveUI;
4 | using System.Reactive;
5 |
6 | namespace AvaloniaSample.ViewModels
7 | {
8 | public abstract class ViewModelBase : ReactiveObject
9 | {
10 | public ViewModelBase()
11 | {
12 | ShutDownCommand = ReactiveCommand.Create(() =>
13 | {
14 | var lifeTime = Application.Current!.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime;
15 | lifeTime!.Shutdown();
16 | });
17 | }
18 | private string _stringValue = "I am MainWindowViewModel";
19 | public string StringValue
20 | {
21 | get { return _stringValue; }
22 | set { this.RaiseAndSetIfChanged(ref _stringValue, value); }
23 | }
24 |
25 | public ReactiveCommand ShutDownCommand
26 | {
27 | get;
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/AvaloniaSample/Views/MainWindow.axaml:
--------------------------------------------------------------------------------
1 |
15 |
16 |
17 |
23 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/src/AvaloniaSample/Views/MainWindow.axaml.cs:
--------------------------------------------------------------------------------
1 | using Avalonia.Controls;
2 |
3 | namespace AvaloniaSample.Views
4 | {
5 | public partial class MainWindow : Window
6 | {
7 | public MainWindow()
8 | {
9 | InitializeComponent();
10 | }
11 | }
12 | }
--------------------------------------------------------------------------------
/src/AvaloniaSample/app.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
8 |
9 |
10 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/src/AvaloniaSample/rd.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/src/Lemon.Hosting.AvaloniauiDesktop.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.10.35027.167
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lemon.Hosting.AvaloniauiDesktop", "Lemon.Hosting.AvaloniauiDesktop\Lemon.Hosting.AvaloniauiDesktop.csproj", "{5CB50B59-FCD0-4872-84A3-EF33F2C10391}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaSample", "AvaloniaSample\AvaloniaSample.csproj", "{AAD40E7B-A2DC-47BD-B3A2-ADACD968E818}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {5CB50B59-FCD0-4872-84A3-EF33F2C10391}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {5CB50B59-FCD0-4872-84A3-EF33F2C10391}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {5CB50B59-FCD0-4872-84A3-EF33F2C10391}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {5CB50B59-FCD0-4872-84A3-EF33F2C10391}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {AAD40E7B-A2DC-47BD-B3A2-ADACD968E818}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {AAD40E7B-A2DC-47BD-B3A2-ADACD968E818}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {AAD40E7B-A2DC-47BD-B3A2-ADACD968E818}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {AAD40E7B-A2DC-47BD-B3A2-ADACD968E818}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {4818C737-7ADF-4202-A4FD-87A0B21471FF}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/src/Lemon.Hosting.AvaloniauiDesktop/AvaloniauiApplicationLifetime.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Controls.ApplicationLifetimes;
3 | using Avalonia.Threading;
4 | using Microsoft.Extensions.DependencyInjection;
5 | using Microsoft.Extensions.Hosting;
6 | using System.Runtime.Versioning;
7 |
8 | namespace Lemon.Hosting.AvaloniauiDesktop
9 | {
10 | ///
11 | /// Provides an implementation that manages the lifetime of a Avaloniaui classic desktop .
12 | /// The instance is created during startup and shut down when the host is stopped.
13 | ///
14 | /// The type of Avaloniaui Application to manage.
15 | [SupportedOSPlatform("windows")]
16 | [SupportedOSPlatform("linux")]
17 | [SupportedOSPlatform("macos")]
18 | public sealed class AvaloniauiApplicationLifetime : IHostLifetime
19 | where TApplication : Application
20 | {
21 | private readonly IHostApplicationLifetime _applicationLifetime;
22 | private readonly TaskCompletionSource