Repository navigation
Interop between ReactiveUI.SourceGenerators ([IViewFor]) and Splat.DependencyInjection.SourceGenerator #4341
|
Hi everyone, I created this discussion because I use both ReactiveUI.SourceGenerators and Splat.DependencyInjection.SourceGenerator in one of my personal projects, and I noticed a behavior that I can't quite wrap my head around, so I'm looking for answers to understand the pros and cons. SummaryWhen I register a View/ViewModel pair via the Context / Environment
ReproView (registered via the IViewFor source generator), as shown in the ReactiveUI.SourceGenerators README: [IViewFor<MyCustomViewModel>(RegistrationType = SplatRegistrationType.PerRequest, ViewModelRegistrationType = SplatRegistrationType.LazySingleton)]
public partial class MyCustomView : UserControl
{
public MyCustomView()
{
InitializeComponent();
}
}ViewModel with a constructor dependency: public partial class MyCustomViewModel : ViewModelBase
{
private readonly IMyService _myService;
public MyCustomViewModel(IMyService myService)
{
_myService = myService;
}
}Service registration via Splat.DI.SourceGenerator: public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.WithInterFont()
.LogToTrace()
.UseReactiveUI(rxui =>
{
rxui.WithRegistration(resolver =>
{
Splat.SplatRegistrations.RegisterLazySingleton<IMyService, MyService>();
Splat.SplatRegistrations.SetupIOC();
resolver.RegisterViewsForViewModelsSourceGenerated();
});
});Observed behaviourWhen the View is resolved (and therefore the VM is instantiated through the registration generated by So I need to use a workaround: public MyCustomViewModel(IMyService myService)
{
_myService = myService
?? Locator.Current.GetService<IMyService>()
?? throw new ArgumentNullException(nameof(myService));
}With this Service Locator fallback in the constructor, everything works. But:
So I'm wondering: is this intended behaviour? If so, what's the reasoning behind it, and what would be the recommended way to combine both generators? Or did I just miss something in the setup? Happy to provide a minimal repro repo if it helps. Thanks! |
Replies: 1 comment
|
In current ReactiveUI.SourceGenerators, Register the view model with Splat.DI.SourceGenerator yourself, for example |
In current ReactiveUI.SourceGenerators,
[IViewFor<T>]only writes theViewModelproperty and theIViewFor<T>members. View registration is done by the ReactiveUI.Binding view locator at build time.RegistrationType,ViewModelRegistrationTypeandRegisterViewsForViewModelsSourceGenerated()no longer exist, and the attribute does not register the view model.Register the view model with Splat.DI.SourceGenerator yourself, for example
SplatRegistrations.Register<MyCustomViewModel>()orRegisterLazySingleton<MyCustomViewModel>(), next toRegisterLazySingleton<IMyService, MyService>(). The generator resolves constructor parameters of every registered type (README, "Constructor Injection"), soI…