adospace / reactorui-maui

MauiReactor is a MVU UI framework built on top of .NET MAUI
MIT License
587 stars 49 forks source link

Constructor dependency injection #25

Closed davidnajar closed 1 year ago

davidnajar commented 1 year ago

First of all, great work! I'm exploring other options for Maui development than basic xaml mvvm and this got my attention (currently debating between mauireactor and mobile blazor bindings).

I saw in the docs that for getting services one should use a service locator pattern. What about constructor DI? Is there any reason to not support it? Maybe I'm missing something which prevents this to work.

Thanks for your great work!

adospace commented 1 year ago

Thanks for your interest,

When I implemented the DI, I found it easier to inject the IServiceProvider inside the component and have the developer call Services.GetRequiredService() where needed (https://adospace.gitbook.io/mauireactor/deep-dives/dependency-injection).

Using the constructor DI in MauiReactor would have required the developer to get the component from the DI container instead of just initiating it, resulting in less readable code.

For example instead of this code:

new HStack
{
    new Component()
}

this:

new HStack
{
    CreateComponent<MyComponent>() //-> where Component base class have the method something like CreateComponent<T>()=>ServiceProvider.GetService<T>();
}

not considering the part where you have to register your types with the DI container (in MVVM pattern makes more sense because usually, you have one view to one view-model while in MVU you generally have a page built of several components). There also could be some more things to adjust when hot-reloading the component, anyway, overall, the main reason is to keep the UI render code as clean as possible.

davidnajar commented 1 year ago

Clear enough, absolutely makes sense. I'm usually against service locator but is true that here is more than justified. I was thinking in an alternative of using fluxor and execute the logic in effects (getting closer to react native + redux).

I'll close this issue as it's all good for now! Thanks!