如何使用Xamarin和Autofac将构造函数依赖项注入到ViewModel中?

ciy*_*n97 6 c# dependency-injection inversion-of-control autofac xamarin.forms

我有一个ViewModel,我想向它注入另一个类。我将Visual Studio与最新版本的Xamarin一起使用。我正在使用Autofac来注册解析依赖项。但是,我是新手,即使遇到的问题很简单,我仍然无法找到解决方案。

这是我要在其中注入另一个类的类:

public IMessagingCenterWrapper MessagingCenterWrapper;

public LoginViewModel(IMessagingCenterWrapper messagingCenterWrapper){
            MessagingCenterWrapper = messagingCenterWrapper;
        }
Run Code Online (Sandbox Code Playgroud)

然后在应用程序的入口点,我有一个函数来初始化容器,该容器注册并解析依赖项

static IContainer container{ get; set; }

public App ()
        {
            InitializeComponent();

            InitializeIOCContainer();
        }

void InitializeIOCContainer()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<LoginViewModel>();
            builder.RegisterType<MessagingCenterWrapper>().As<IMessagingCenterWrapper>();
            container = builder.Build();

            var wrapper = container.Resolve<IMessagingCenterWrapper>();
            var viewModel = container.Resolve<LoginViewModel>();
        }
Run Code Online (Sandbox Code Playgroud)

但是在登录视图中的行上构建时出现错误:

 BindingContext = new LoginViewModel();
Run Code Online (Sandbox Code Playgroud)

我收到错误消息是因为我没有在调用中初始化参数。

但是,如果这样做,我就不会破坏IoC模式的整个原理。最终,新的类调用将与其他依赖项嵌套在一起,我想避免这种情况。

所以我的问题是:如何实际将class参数注入构造函数中?

Ste*_*cus -4

这实际上是服务定位器注入,因为注入的元素是消息中心服务。那是好消息。

您不必传入服务构造函数来查看模型构造函数。只需在您需要的地方请求服务即可:

public LoginViewModel()  
{  
   MessagingCenterWrapper = App.Container.Resolve<IMessagingCenterWrapper>();  
}  
Run Code Online (Sandbox Code Playgroud)

不要将视图模型粘贴到 AutoFac 中,除非它们确实是全局的。这种假IOC存在很多问题。

为了使整体更容易,怎么样:

// 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 !!!! }
}  
Run Code Online (Sandbox Code Playgroud)

这些评论的完整代码位于https://github.com/marcusts/xamarin-forms-annoyances。请参阅名为 AwaitAsyncAntipattern.sln 的解决方案。

GitHub 站点还提供了有关此主题的更详细讨论的链接。