How do I inject a constructor dependency into a ViewModel using Xamarin and Autofac?

泄露秘密 提交于 2019-12-05 08:19:17

This is actually a service locator injection, since the injected element is a messaging center service. That's good news.

You don't have to pass in service constructors to view model constructors. Just request the service where you need it:

public LoginViewModel()  
{  
   MessagingCenterWrapper = App.Container.Resolve<IMessagingCenterWrapper>();  
}  

Don't stick the view models into AutoFac unless they are indeed global. There are a lot of problems with this sort of fake IOC.

To make it easier overall, how about this:

// MUST BE PUBLIC 
public static IContainer Container{ get; set; }

static App()  
{
   InitializeIOCContainer();  
} 

public App () 
{    
   InitializeComponent(); 
}

private static void InitializeIOCContainer() 
{    
   var builder = new ContainerBuilder();    
   builder.RegisterType<MessagingCenterWrapper>().As<IMessagingCenterWrapper>();
   Container = builder.Build();

   // Don't stick view models in the container unless you need them globally, which is almost never true !!!

   // Don't Resolve the service variable until you need it !!!! }
}  

The complete code for these remarks is at https://github.com/marcusts/xamarin-forms-annoyances. See the solution called AwaitAsyncAntipattern.sln.

The GitHub site also provides links to a more detailed discussion on this topic.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!