Skip to content

Commit c778bcb

Browse files
committed
Implementação | Injeção de dependência
1 parent 1fbbd13 commit c778bcb

File tree

10 files changed

+210
-138
lines changed

10 files changed

+210
-138
lines changed

.editorconfig

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
[*.cs]
2+
3+
# CS8602: Desreferência de uma referência possivelmente nula.
4+
dotnet_diagnostic.CS8602.severity = none

ExplorandoMarte.sln

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExplorandoMarte", "Exploran
77
EndProject
88
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExplorandoMarte.Tests", "ExplorandoMarte.Tests\ExplorandoMarte.Tests.csproj", "{6E88F476-A7C8-4A6F-9395-5C815FFA75E8}"
99
EndProject
10+
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}"
11+
ProjectSection(SolutionItems) = preProject
12+
.editorconfig = .editorconfig
13+
EndProjectSection
14+
EndProject
1015
Global
1116
GlobalSection(SolutionConfigurationPlatforms) = preSolution
1217
Debug|Any CPU = Debug|Any CPU
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
using ExplorandoMarte.Commands;
2+
using ExplorandoMarte.Interfaces;
3+
using ExplorandoMarte.Invokers;
4+
using ExplorandoMarte.Models;
5+
using Microsoft.Extensions.DependencyInjection;
6+
7+
namespace ExplorandoMarte.View
8+
{
9+
public class Application : IApplication
10+
{
11+
private readonly IController Controller;
12+
private readonly IServiceProvider ServiceProvider;
13+
14+
public Application(IController controller, IServiceProvider serviceProvider)
15+
{
16+
Controller = controller;
17+
ServiceProvider = serviceProvider;
18+
}
19+
private T Resolve<T>() => ServiceProvider.GetRequiredService<T>();
20+
21+
//Resolve<IController>().RegistrarLog("Explorando Marte");
22+
//ServiceProvider.GetRequiredService<IController>().RegistrarLog("Explorando Marte");
23+
24+
public void Run()
25+
{
26+
try
27+
{
28+
Controller.InicializarLog();
29+
30+
Controller.RegistrarLog("Iniciando a exploração de Marte...");
31+
32+
Controller.RegistrarLog("Informe as Coordenadas do Planalto: ");
33+
34+
int upperRightX, upperRightY = 0;
35+
36+
var plateauCoordinates = Console.ReadLine().Split(' ');
37+
38+
try
39+
{
40+
upperRightX = int.Parse(plateauCoordinates[0]);
41+
upperRightY = int.Parse(plateauCoordinates[1]);
42+
}
43+
catch (Exception)
44+
{
45+
throw new Exception("Coordenadas Inválidas");
46+
}
47+
48+
var planalto = new Planalto(upperRightX, upperRightY);
49+
50+
Controller.RegistrarLog("Coordenadas do Planalto: " + planalto.ObterCoordenadasSuperiores());
51+
52+
List<Rover> rovers = new List<Rover>();
53+
54+
while (rovers.Count < 2)
55+
{
56+
Controller.RegistrarLog("Informe a posição inicial do Rover: ");
57+
58+
Console.WriteLine("------------------------------------------------------");
59+
Console.WriteLine("Exemplo de posição inicial válida: ");
60+
Console.WriteLine("1 2 N");
61+
Console.WriteLine("X = 1, Y = 2, Direção = Norte");
62+
Console.WriteLine("Direções válidas: N, S, E, W");
63+
64+
var initialPosition = Console.ReadLine();
65+
66+
if (string.IsNullOrEmpty(initialPosition) || string.IsNullOrWhiteSpace(initialPosition))
67+
{
68+
throw new ArgumentException("Posição Inválida para o Rover.", initialPosition);
69+
}
70+
71+
var positionParts = initialPosition.Split(' ');
72+
73+
int x = int.Parse(positionParts[0]);
74+
int y = int.Parse(positionParts[1]);
75+
76+
if (planalto.PosicaoOcupada(x: x, y: y))
77+
{
78+
throw new InvalidOperationException(string.Format("Posição já ocupada por outra sonda Rover {0}.", planalto.ObterRoverPorLocalizacao(x, y).Nome));
79+
}
80+
81+
char direction = char.Parse(positionParts[2].ToUpperInvariant());
82+
83+
var rover = new Rover(x, y, direction);
84+
85+
rover.SetPlanalto(planalto);
86+
87+
planalto.AdicionarRover(rover);
88+
89+
Controller.RegistrarLog("Posição Inicial do Rover: " + rover.GetPosition());
90+
91+
Controller.RegistrarLog("Informe a sequência de instruções para o Rover: ");
92+
93+
var instructions = Console.ReadLine();
94+
95+
Controller.RegistrarLog("Instruções: " + instructions);
96+
97+
var invoker = new CommandInvoker();
98+
99+
foreach (var instruction in instructions)
100+
{
101+
try
102+
{
103+
ICommand command = instruction switch
104+
{
105+
'L' => new TurnLeftCommand(rover),
106+
'R' => new TurnRightCommand(rover),
107+
'M' => new MoveCommand(rover),
108+
_ => throw new ArgumentException("Instrução inválida. As instruções válidas são: L, R, M.")
109+
};
110+
111+
invoker.AddCommand(command);
112+
113+
invoker.ExecuteCommands();
114+
115+
Controller.RegistrarLog("Instrução executada: " + instruction);
116+
}
117+
catch (Exception ex)
118+
{
119+
Controller.RegistrarErro(ex.Message);
120+
}
121+
}
122+
123+
rovers.Add(rover);
124+
}
125+
126+
}
127+
catch (Exception ex)
128+
{
129+
Controller.RegistrarErro(ex.Message);
130+
}
131+
finally
132+
{
133+
Controller.RegistrarLog("Exploração de Marte finalizada.");
134+
}
135+
136+
}
137+
}
138+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using ExplorandoMarte.Controllers;
2+
using ExplorandoMarte.Interfaces;
3+
using ExplorandoMarte.Models;
4+
using ExplorandoMarte.View;
5+
using Microsoft.Extensions.DependencyInjection;
6+
using Microsoft.Extensions.Hosting;
7+
8+
9+
namespace ExplorandoMarte.Configuration
10+
{
11+
public static class DependencyInjection
12+
{
13+
public static IServiceCollection ResolveDependencies(this IServiceCollection services)
14+
{
15+
services.AddScoped<IController, Controller>();
16+
services.AddScoped<ILogger, Logger>();
17+
services.AddSingleton<IApplication, Application>();
18+
19+
return services;
20+
}
21+
}
22+
}

ExplorandoMarte/Controllers/Controller.cs

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,6 @@ namespace ExplorandoMarte.Controllers
77
{
88
public class Controller : MainController
99
{
10-
private static Controller _instance;
11-
1210
public RoverService RoverService { get; private set; }
1311

1412
private static readonly object _lock = new object();
@@ -18,21 +16,6 @@ public Controller(ILogger logger) : base(logger)
1816
RoverService = new RoverService();
1917
}
2018

21-
public static Controller Instance
22-
{
23-
get
24-
{
25-
lock (_lock)
26-
{
27-
if (_instance == null)
28-
{
29-
_instance = new Controller(logger: Logger.Instance);
30-
}
31-
return _instance;
32-
}
33-
}
34-
}
35-
3619
public bool PosicaoOcupada(Planalto planalto, int x, int y)
3720
{
3821
return planalto.PosicaoOcupada(x, y);

ExplorandoMarte/ExplorandoMarte.csproj

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,10 @@
77
<Nullable>enable</Nullable>
88
</PropertyGroup>
99

10+
<ItemGroup>
11+
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.3" />
12+
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.3" />
13+
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="9.0.3" />
14+
</ItemGroup>
15+
1016
</Project>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace ExplorandoMarte.Interfaces
8+
{
9+
public interface IApplication
10+
{
11+
public void Run();
12+
}
13+
}

ExplorandoMarte/Interfaces/IController.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ namespace ExplorandoMarte.Interfaces
99
{
1010
public interface IController
1111
{
12+
public void InicializarLog();
1213
public void RegistrarLog(string mensagem);
1314

1415
public void RegistrarErro(string mensagem);

ExplorandoMarte/Program.cs

Lines changed: 20 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -5,123 +5,39 @@
55
using ExplorandoMarte.Models;
66
using System;
77
using System.Collections.Generic;
8+
using Microsoft.Extensions.DependencyInjection;
9+
using Microsoft.Extensions.Hosting;
10+
using ExplorandoMarte.View;
11+
using ExplorandoMarte.Configuration;
812

913
namespace ExplorandoMarte
1014
{
1115
public class Program
1216
{
1317
public static void Main(string[] args)
1418
{
15-
try
16-
{
17-
Controller.Instance.InicializarLog();
18-
19-
Controller.Instance.RegistrarLog("Iniciando a exploração de Marte...");
20-
21-
Controller.Instance.RegistrarLog("Informe as Coordenadas do Planalto: ");
22-
23-
int upperRightX, upperRightY = 0;
24-
25-
var plateauCoordinates = Console.ReadLine().Split(' ');
26-
27-
try
28-
{
29-
upperRightX = int.Parse(plateauCoordinates[0]);
30-
upperRightY = int.Parse(plateauCoordinates[1]);
31-
}
32-
catch (Exception)
33-
{
34-
throw new Exception("Coordenadas Inválidas");
35-
}
36-
37-
var planalto = new Planalto(upperRightX, upperRightY);
38-
39-
Controller.Instance.RegistrarLog("Coordenadas do Planalto: " + planalto.ObterCoordenadasSuperiores());
40-
41-
List<Rover> rovers = new List<Rover>();
42-
43-
while (rovers.Count < 2)
44-
{
45-
Controller.Instance.RegistrarLog("Informe a posição inicial do Rover: ");
46-
47-
Console.WriteLine("------------------------------------------------------");
48-
Console.WriteLine("Exemplo de posição inicial válida: ");
49-
Console.WriteLine("1 2 N");
50-
Console.WriteLine("X = 1, Y = 2, Direção = Norte");
51-
Console.WriteLine("Direções válidas: N, S, E, W");
52-
53-
var initialPosition = Console.ReadLine();
54-
55-
if (string.IsNullOrEmpty(initialPosition) || string.IsNullOrWhiteSpace(initialPosition))
56-
{
57-
throw new ArgumentException("Posição Inválida para o Rover.", initialPosition);
58-
}
59-
60-
var positionParts = initialPosition.Split(' ');
61-
19+
//IHost _host = Host.CreateDefaultBuilder(args)
20+
// .ConfigureServices((hostContext, services) =>
21+
// {
22+
// services.ResolveDependencies();
23+
// })
24+
// .Build();
6225

63-
int x = int.Parse(positionParts[0]);
64-
int y = int.Parse(positionParts[1]);
26+
//var app = _host.Services.GetService<IApplication>();
6527

66-
if(planalto.PosicaoOcupada(x: x, y: y))
67-
{
68-
throw new InvalidOperationException(string.Format("Posição já ocupada por outra sonda Rover {0}.",planalto.ObterRoverPorLocalizacao(x,y).Nome));
69-
}
28+
//app.Run();
7029

71-
char direction = char.Parse(positionParts[2].ToUpperInvariant());
30+
var builder = Host.CreateDefaultBuilder(args);
7231

73-
var rover = new Rover(x, y, direction);
74-
75-
rover.SetPlanalto(planalto);
76-
77-
planalto.AdicionarRover(rover);
78-
79-
Controller.Instance.RegistrarLog("Posição Inicial do Rover: " + rover.GetPosition());
80-
81-
Controller.Instance.RegistrarLog("Informe a sequência de instruções para o Rover: ");
82-
83-
var instructions = Console.ReadLine();
84-
85-
Controller.Instance.RegistrarLog("Instruções: " + instructions);
86-
87-
var invoker = new CommandInvoker();
88-
89-
foreach (var instruction in instructions)
90-
{
91-
try
92-
{
93-
ICommand command = instruction switch
94-
{
95-
'L' => new TurnLeftCommand(rover),
96-
'R' => new TurnRightCommand(rover),
97-
'M' => new MoveCommand(rover),
98-
_ => throw new ArgumentException("Instrução inválida. As instruções válidas são: L, R, M.")
99-
};
100-
101-
invoker.AddCommand(command);
102-
103-
invoker.ExecuteCommands();
104-
105-
Controller.Instance.RegistrarLog("Instrução executada: " + instruction);
106-
}
107-
catch (Exception ex)
108-
{
109-
Controller.Instance.RegistrarErro(ex.Message);
110-
}
111-
}
32+
builder.ConfigureServices((services) =>
33+
{
34+
services.ResolveDependencies();
35+
});
11236

113-
rovers.Add(rover);
114-
}
37+
var app = builder.Build();
11538

116-
}
117-
catch (Exception ex)
118-
{
119-
Controller.Instance.RegistrarErro(ex.Message);
120-
}
121-
finally
122-
{
123-
Controller.Instance.RegistrarLog("Exploração de Marte finalizada.");
124-
}
39+
app.Services.GetService<IApplication>().Run();
12540
}
41+
12642
}
12743
}

0 commit comments

Comments
 (0)