FreshMvvm中的控制反转(IOC)

时间:2018-09-27 07:11:10

标签: c# xamarin mvvm dependency-injection inversion-of-control

关于IOC,我阅读了以下定义并注册了interface,但我确实无法理解

  

我们不需要包含我们自己的IOC容器,FreshMvvm带有一个   内置IOC容器。它在下面使用TinyIOC,但是   不同的命名以避免冲突。

与FreshIOC的接口注册,如果您看到此代码,则在应用程序的开始阶段实现该实现

public App()  
{  
    InitializeComponent();  

    //Interface rgistration with FreshIOC  
    FreshIOC.Container.Register<IContactRepository, ContactRepository>();  
    FreshIOC.Container.Register<IValidator, ContactValidator>();  

    //var mainPage = FreshPageModelResolver.ResolvePageModel<AddContactPageModel>();  
    //MainPage = new FreshNavigationContainer(mainPage);  
} 

为什么我们需要注册接口,如果没有注册,那将是真正的实现呢?实施此原则有什么好处。我关注的This文章。

2 个答案:

答案 0 :(得分:3)

内置的IOC容器是TinyIOC的抽象。

要通过FreshMvvm抽象在TinyIOC容器中注册类型:

FreshIOC.Container.Register<ISomeInterface, SomeImplementation>();

要稍后使用它:

// Gets object of type SomeImplementation
var instanceOfConcreteType = FreshIOC.Container.Resolve<ISomeInterface>();

以下是讨论IOC 的帖子:What is Inversion of Control?

答案 1 :(得分:3)

如果您已经在Xamarin.Forms中使用了DependencySerices,那么您已经大部分使用了。从Xamarin.Forms的角度解释

让我们假设您的ContentPage需要一个Network类来检查是否存在网络连接,传统的实现方式是使用new关键字并获取实例,以便您可以调用其方法。

public MyContentPage : ContentPage
{
    private Network network;
    public MyContentPage()
    {
        //..
        network = new Network();
    }
}

public Network()
{
    public bool HasConnectivity() { ... }
}

这没有什么错,但是如果Network类内部需要一个Log类怎么办?并且MyContentPage还需要Log类和Dialog类吗?这需要在您的所有其他50页中完成??依赖注入解决了这些以及更多问题!

您创建接口及其实现,然后将其注册到容器中。然后容器为您解决所有依赖项!

public MyContentPage : ContentPage
{
    private INetwork _network;
    private IDialog _dialog;
    public MyContentPage(INetwork network, IDialog dialog)
    {
        //..
        _network = network;
        _dialog = dialog;
    }
}    

public Network(ILog log)
{
    public bool HasConnectivity() { ... }
}

如果您已注册所有依赖项,Container将处理依赖关系图并为您解决它们。如果Container无法解析图形(可能是由于您未注册或可能是循环依赖项),则会抛出异常。

乍看之下,这似乎完全没有必要,但是随着您的应用程序的发展,MVVM与DI结合可以更强大,更轻松地进行开发。

我所解释的只是DI的一小部分,您可以在此awesome Martin Fowler post

中了解有关IoC和DI的更多信息