Created
August 8, 2023 11:15
-
-
Save profiiqus/ab6930ad9d2a072bede843670b2a8892 to your computer and use it in GitHub Desktop.
Microsoft.Extensions.DependencyInjection Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace DependencyInjectionTest; | |
public interface IDatabaseService | |
{ | |
public void DoStuff(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace DependencyInjectionTest; | |
public class MssqlDatabaseService : IDatabaseService | |
{ | |
private string Name { get; set; } | |
public MssqlDatabaseService(string name) | |
{ | |
Name = name; | |
} | |
public void DoStuff() | |
{ | |
Console.WriteLine($"Hello, my name is {Name}!"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Extensions.DependencyInjection; | |
namespace DependencyInjectionTest; | |
public abstract class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var services = Startup.BuildServices(); | |
var databaseService = services.GetService<IDatabaseService>(); | |
databaseService?.DoStuff(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Extensions.DependencyInjection; | |
namespace DependencyInjectionTest; | |
public static class Startup | |
{ | |
public static ServiceProvider BuildServices() | |
{ | |
var services = new ServiceCollection() | |
.AddSingleton<IDatabaseService>(new MssqlDatabaseService("Tester")); | |
return services.BuildServiceProvider(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment