How to use autofac in an UWP app?

后端 未结 4 759
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 18:58

I am using autofac in an UWP application. In my App instance, I am setting up the dependency, like this:

public sealed partial class App
{
   privat         


        
4条回答
  •  遇见更好的自我
    2021-02-04 19:38

    Just to add to Nkosi's fantastic and deep question, when I create pages in UWP I use the following pattern:

    private IDependency _dep1;
    
    public Page()
    {
        _dep1 = ServiceLocator.Current.Resolve();
        init();
    }
    
    public Page(IDependency dep1, ...)
    {
        _dep1 = dep1;
        init();
    }
    
    private void init()
    {
        /* Do initialization here, i.e. InitializeComponent() */
    }
    

    The benefit that this gives is that it allows you to still write testable code because you inject your dependencies in your unit tests. The service locator only runs at run time.

    As Nkosi points out, the Frame is responsible ultimately for instantiation of the Page via the Navigate method. At the point that Microsoft exposes the ability to intercept or override the instantiation, it'll be possible to have a DI container do the instantiation. Until then, we're stuck with using a Service Locator pattern at runtime.

提交回复
热议问题