我正在重构一个块代码,并想对我的服务使用构造函数注入。到目前为止,我的服务得到了空异常(可能是因为我还没有容器)。有人知道我该如何实现吗?
namespace RampantRobots_NextLvl
{
class Program
{
private static IBoardService _boardService;
private static IPlayerService _playerService;
public Program(IBoardService boardService,IPlayerService playerService)
{
_boardService = boardService;
_playerService = playerService;
}
static void Main(string[] args)
{
var player = _playerService.Create(1, 1);
var board = _boardService.Create(5,10,3,3,player);
_boardService.Draw(player, board);
_boardService.MovePlayer(player, board);
Console.ReadLine();
}
}
}
答案 0 :(得分:0)
即使没有容器,代码仍然可以使用Pure DI as described here
首先,最好使那些显式依赖项实例字段而不是静态字段。
private readonly IBoardService _boardService;
private readonly IPlayerService _playerService;
所需的大部分功能都应重构为一个方法,该方法将在初始化类后立即调用。
public void Invoke() {
var player = _playerService.Create(1, 1);
var board = _boardService.Create(5, 10, 3, 3, player);
_boardService.Draw(player, board);
_boardService.MovePlayer(player, board);
//...
}
这使Main
成为合成根,在此创建所有依赖项并将其注入到依赖类中,并调用所需的功能。
完整示例
class Program {
private readonly IBoardService _boardService;
private readonly IPlayerService _playerService;
public Program(IBoardService boardService, IPlayerService playerService) {
_boardService = boardService;
_playerService = playerService;
}
public void Invoke() {
var player = _playerService.Create(1, 1);
var board = _boardService.Create(5, 10, 3, 3, player);
_boardService.Draw(player, board);
_boardService.MovePlayer(player, board);
//...
}
static void Main(string[] args) {
//Assuming default implementations
IBoardService boardService = new BoardService();
IPlayerService playerService = new PlayerService();
//Explicit dependency injection via constructor
var program = new Program(boardService, playerService);
//invoke desired functionality
program.Invoke();
Console.ReadLine();
}
}
当容器最终引入(如果有的话)时,仅需要重新组合根来注册依赖项。