简体   繁体   English

uwp 和 c# 和 mvvm 如何做控制反转(依赖注入)

[英]uwp with c# and mvvm how to do inversion of control (dependency injection)

so most of my progamming has been done in java where i used a lot of IoC and DPI by injecting all the necessary depencies to the constructors of the newly created objects from the main method.所以我的大部分编程都是在 java 中完成的,在那里我使用了大量的 IoC 和 DPI,将所有必要的依赖项注入到 main 方法中新创建的对象的构造函数中。 so i injected all the repositories into the services, then the services into the controllers.所以我将所有存储库注入服务,然后将服务注入控制器。 in this way i only created one instance of each dependency and injected them wherever they were needed.通过这种方式,我只创建了每个依赖项的一个实例,并将它们注入到需要它们的地方。

in java i do it like this:在 java 我这样做:

public class Main {

    public static void main(String[] args) {

        InterfaceRepository<Booking> bookingInterface = new BookingRepository();
        InterfaceRepository<User> userInterface = new UserRepository();
        
        InterfaceBookingService interfaceBookingService = new BookingService(bookingInterface, userInterface);
        InterfaceUserService interfaceUserService = new UserService(userInterface);
        
        BookingController bookingController = new BookingController(interfaceBookingService, interfaceUserService);
        UserController userController = new UserController(interfaceUserService)

    }

}

in uwp i'm completely lost on how to do the same as i did in java.在 uwp 中,我完全不知道如何像在 java 中那样做。 how and where are the viewmodels even instanced and how can i inject the repositories into the viewmodels;视图模型是如何以及在哪里实例化的,我如何将存储库注入到视图模型中; if some of my repositories are needed by several of the viewmodels, can i inject the same instance of the repositories to the different viewmodels?如果几个视图模型需要我的一些存储库,我可以将相同的存储库实例注入不同的视图模型吗? i want to be able to test my viewmodels, so i want to have the possibility to be flexible with what i inject as well.我希望能够测试我的视图模型,所以我希望能够灵活地处理我注入的内容。

i'm sorry i don't have any code, this is because i can't even get started coding in uwp with c# and mvvm without finding out how to be able to do IoC and follow the SOLID principles对不起,我没有任何代码,这是因为我什至无法开始在 uwp 中使用 c# 和 mvvm 进行编码,而没有了解如何能够进行 IoC 并遵循 SOLID 原则

About MVVM in UWP, you could refer to the document .关于 UWP 中的 MVVM,可以参考文档 There are samples in the document you could view that where the viewmodles are instanced.文档中有示例,您可以查看实例化视图模型的位置。

You could use Microsoft.Extensions.DependencyInjection NuGet package to do the dependency injection.您可以使用Microsoft.Extensions.DependencyInjection NuGet package 进行依赖注入。

Please check the following steps: 1.Create the MVVM architecture in a C# UWP project.请检查以下步骤: 1. 在 C# UWP 项目中创建 MVVM 架构。 2.Click Tools in menu, select the option NuGet Package Manager > Manage NuGet Package for Solution… > Browse , enter Microsoft.Extensions.DependencyInjection in search box, install the package for your project. 2.Click Tools in menu, select the option NuGet Package Manager > Manage NuGet Package for Solution… > Browse , enter Microsoft.Extensions.DependencyInjection in search box, install the package for your project. 3.Create Container object which maintains all of the dependencies that can be resolved anywhere in the application. 3.创建Container object,它维护所有可以在应用程序的任何地方解决的依赖关系。

//App.xaml.cs
public App()
{
    this.InitializeComponent();
    this.Suspending += OnSuspending;
    Container = ConfigureDependencyInjection();
}
public IServiceProvider Container { get; }

IServiceProvider ConfigureDependencyInjection()
{
    var serviceCollection = new ServiceCollection();

    serviceCollection.AddTransient<IMessageService, MessageService>();

    return serviceCollection.BuildServiceProvider();
}

4.Create the MessageService class and the IMessageService interface. 4.创建MessageService class和IMessageService接口。

//Add a new class to create the interface and class
public interface IMessageService
{
    string GetMessage();
}
public class MessageService : IMessageService
{
    public string GetMessage()
    {
        return "Hello from Message Service & Dependency Injection";
    }
}

5.Register MessageService to Container (referring to the code in step 3 ). 5.将MessageService注册到Container (参考步骤3中的代码)。 6.Inject MessageService into your viewmodel class such as MainViewModel class. 6. 将MessageService注入您的视图模型 class,例如MainViewModel class。

public class MainViewModel
{
    protected IMessageService MessageService { get; }
    public string Message { get => MessageService.GetMessage(); }
    public MainViewModel(IMessageService messageService)
    {
        MessageService = messageService;
        ……
    }
    ……
}

7.Resolve the MainViewModel , and inject the dependencies by using ActivatorUtilities function to inject parameters into the constructor. 7.Resolve MainViewModel ,并通过ActivatorUtilities function向构造函数注入参数注入依赖。

//MainPage.xaml.cs
public MainPage()
{
    this.InitializeComponent();
    var container = ((App)App.Current).Container;
    DataContext = ActivatorUtilities.GetServiceOrCreateInstance(container, typeof(MainViewModel));
}

8.Show the message in page. 8.在页面中显示消息。

//MainPage.xaml
<Grid>
    <TextBlock Text="{Binding Message}" Margin="10" FontSize="20"/>
</Grid>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM