在WPF应用程序中组合MVVM和依赖注入,可以遵循以下步骤:
var builder = new ContainerBuilder();
builder.RegisterType<Repository>().As<IRepository>();
builder.RegisterType<ViewModel>();
var container = builder.Build();
public class ViewModelLocator
{
private IContainer _container;
public ViewModelLocator()
{
var builder = new ContainerBuilder();
builder.RegisterType<Repository>().As<IRepository>();
builder.RegisterType<ViewModel>();
_container = builder.Build();
}
public ViewModel MainViewModel => _container.Resolve<ViewModel>();
}
<local:ViewModelLocator />
</Window.DataContext>
public class ViewModel
{
private IRepository _repository;
public ViewModel(IRepository repository)
{
_repository = repository;
}
}
通过以上步骤,可以在WPF应用程序中组合MVVM和依赖注入,实现松耦合、可测试和可维护的代码。
领取专属 10元无门槛券
手把手带您无忧上云