-1

I have a Win UI3 project which declares a generic host in the main app which is used for dependency injection, etc. The main application will support many different document types, to keep it more manageable I'd like to separate the code and UI (page XAMLs and View Models) for each document type into a separate libraries.

Within the main app the pages are instantiated by the Frame.Navigate method, then the code behind for that page creates the view model using Dependency Injection (App.Host.Services.GetService(typeof(T)) as T; where Host is a static property defined in the app). However, when the frame is defined in a library it doesn't have access to the Host.

The following works, but it's horrendous. Is there a better method?

var apptype = System.Reflection.Assembly.GetEntryAssembly().GetType("SWFieldData.App");
PropertyInfo propertyInfo = apptype.GetProperty("_host", BindingFlags.NonPublic | BindingFlags.Static);
var _host = (Microsoft.Extensions.Hosting.IHost)propertyInfo.GetValue(null, null);
ViewModel = _host.Services.GetService(typeof(SetupDataViewModel)) as SetupDataViewModel;
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Russ_S
  • 1
  • 1
  • `App.Host.Services.GetService` is not dependency injection. It is a Service Locator - antipattern. – Alexander Petrov Jun 27 '22 at 01:25
  • DI will inject `IServiceProvider` so you don't need to use a global variable to find it. But you should define your dependencies in your constructor as much as possible. However Frame.Navigate isn't particularly usable with DI (eg https://stackoverflow.com/questions/59186481/how-do-you-instantiate-pages-that-have-constructors-in-uwp / https://github.com/microsoft/microsoft-ui-xaml/issues/693) – Jeremy Lakeman Jun 27 '22 at 02:52
  • @Russ_S: Move the `Host` property to the separate library? – mm8 Jun 27 '22 at 12:46
  • @mm8: Thanks! I thought about moving the Host to another library, and suspect I may end up going that route. – Russ_S Jun 28 '22 at 13:52
  • @Jeremy Lakeman: Thanks! I hadn't found that post, it helps. – Russ_S Jun 28 '22 at 13:53

1 Answers1

0

However, when the frame is defined in a library it doesn't have access to the Host.

Then you should move the host of the services to the library itself, or another library that is referenced from the library which needs to be able to resolve the services.

mm8
  • 163,881
  • 10
  • 57
  • 88