di injection

main
syneffort 2 years ago
parent 2a2319833a
commit b469188f28
  1. 17
      MySolution/ConsoleApp/Program.cs
  2. 2
      MySolution/ConsoleApp/Samples/CalculateSample.cs
  3. 58
      MySolution/ConsoleApp/Samples/DISample.cs
  4. 2
      MySolution/ConsoleApp/Samples/EventSample.cs
  5. 2
      MySolution/ConsoleApp/Samples/MessagePrinterSample.cs
  6. 4
      MySolution/ConsoleApp/Samples/StringLengthSample.cs

@ -1,4 +1,8 @@
using Samples;
using Samples.Calculate;
using Samples.DI;
using Samples.Event;
using Samples.MessagePrinter;
using Samples.StringLength;
namespace ConsoleApp;
class Program
@ -15,16 +19,23 @@ class Program
#region Callback
// StringLength.Sample();
// StringLengthSample.Sample();
#endregion
#region Event
EventSample.Sample();
// EventSample.Sample();
#endregion
#region Dependency Injection
DISample.Sample();
#endregion
}
}

@ -1,6 +1,6 @@
using System;
namespace Samples
namespace Samples.Calculate
{
class CalculateSample
{

@ -0,0 +1,58 @@
namespace Samples.DI
{
class DISample
{
public static void Sample()
{
DIContainer container = new DIContainer();
container.Register<IService, Service>();
Client client = new Client(container.Resolve<IService>());
client.Run();
}
}
public interface IService
{
void DoSomething();
}
public class Service : IService
{
public void DoSomething()
{
Console.WriteLine("Service is doing something...");
}
}
public class Client
{
private readonly IService _service;
public Client(IService service)
{
_service = service;
}
public void Run()
{
_service.DoSomething();
}
}
public class DIContainer
{
private readonly Dictionary<Type, Type> _typemappings = new Dictionary<Type, Type>();
public void Register<TInterface, TImplementation>()
{
_typemappings[typeof(TInterface)] = typeof(TImplementation);
}
public TInterface Resolve<TInterface>()
{
Type implementationType = _typemappings[typeof(TInterface)];
return (TInterface)Activator.CreateInstance(implementationType);
}
}
}

@ -1,6 +1,6 @@
using System;
namespace Samples
namespace Samples.Event
{
public delegate void CustomEventHandler(object sender, EventArgs e);

@ -2,7 +2,7 @@ using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Samples
namespace Samples.MessagePrinter
{
class MessagePrinterSample
{

@ -1,8 +1,8 @@
using System;
namespace Samples
namespace Samples.StringLength
{
class StringLength
class StringLengthSample
{
public static void Sample()
{
Loading…
Cancel
Save