如果不用现成的依赖注入框架和包,你可以手动实现依赖注入。以下是一个手动实现依赖注入的示例,包括了配置依赖关系和注入属性。
### 1. 手动配置依赖关系
首先,你需要一个简单的依赖注入容器来管理服务的创建和生命周期。这里是一个非常简化的版本:
csharp
public class SimpleContainer
{
private readonly Dictionary<Type, Func<object>> _registrations = new Dictionary<Type, Func<object>>();public void Register<TService>(Func<TService> factory)
{
_registrations[typeof(TService)] = () => factory();
}public TService Resolve<TService>()
{
return (TService)_registrations[typeof(TService)]();
}
}
2. 配置和使用手动的依赖注入容器
在应用程序启动时配置依赖关系并进行注入:
using System;
using System.Windows;
using Zhaoxi.BMS.ViewModels;
using Zhaoxi.BMS.Base;namespace Zhaoxi.BMS
{
public partial class App : Application
{
public static SimpleContainer Container { get; private set; }protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
ConfigureContainer();var mainWindow = Container.Resolve<MainWindow>();
var mainViewModel = Container.Resolve<MainViewModel>();mainWindow.DataContext = mainViewModel;
mainWindow.Show();
}private void ConfigureContainer()
{
Container = new SimpleContainer();
Container.Register(() => new MainWindow());
Container.Register(() => new MainViewModel { NavCommand = new Command() });
}
}
}
### 3. 修改 `MainViewModel` 类以支持属性注入
修改 `MainViewModel` 类以支持属性注入:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Zhaoxi.BMS.Base;
using Zhaoxi.BMS.Models;namespace Zhaoxi.BMS.ViewModels
{
public class MainViewModel : NotifyBase
{
public static List<MainModel> arg = new List<MainModel>();#region Monitor页面的数据
public List<string> BatteryGroup { get; set; } = new List<string>();
#endregionprivate object _pageObject;
public object PageObject
{
get { return _pageObject; }
set { SetProperty(ref _pageObject, value); }
}private ICommand _navCommand;
public ICommand NavCommand
{
get { return _navCommand; }
set
{
_navCommand = value;
if (_navCommand is Command command)
{
command.DoExecute = SwitchPage;
}
}
}public MainViewModel()
{
for (int i = 0; i < 100; i++)
{
BatteryGroup.Add(i.ToString());
}
}private void SwitchPage(object page)
{
Type type = Assembly.GetExecutingAssembly().GetType("Zhaoxi.BMS.Views.Pages." + page.ToString());
this.PageObject = Activator.CreateInstance(type);
}
}
}
```
### 4. 确保 `Command` 类实现了 `ICommand` 接口
确保 `Command` 类的定义如下:
```csharp
using System;
using System.Windows.Input;namespace Zhaoxi.BMS.Base
{
public class Command : ICommand
{
public event EventHandler? CanExecuteChanged;public bool CanExecute(object? parameter)
{
return true;
}public void Execute(object? parameter)
{
DoExecute?.Invoke(parameter);
}public Action<object> DoExecute { get; set; }
public Command(Action<object> doExecute)
{
DoExecute = doExecute;
}public Command() : this(null)
{
}
}
}
```
### 总结
通过以上步骤,我们手动实现了一个简单的依赖注入容器,并使用它来注入 `MainViewModel` 和 `Command`。虽然这种方式比使用现成的 DI 框架更繁琐,但它展示了依赖注入的基本原理,并且不依赖外部库。