Created
September 21, 2023 07:01
-
-
Save unseensenpai/56cb4637de997ca89d2952b05767b3a1 to your computer and use it in GitHub Desktop.
DevExpress WinForm DI/IoC Sample
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 IoC.DI.WinForm.Sample.Configuration; | |
namespace Microsoft.Extensions.DependencyInjection | |
{ | |
public static class DependencyInjectionResolver | |
{ | |
public static IServiceCollection AddServiceModules(this IServiceCollection services) => | |
services | |
.AddFormModule() | |
.AddEmployeeModule() | |
; | |
} | |
} |
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 IoC.DI.WinForm.Sample.Contracts; | |
using IoC.DI.WinForm.Sample.Services; | |
namespace Microsoft.Extensions.DependencyInjection | |
{ | |
public static class EmployeeConfigurationExtensions | |
{ | |
public static IServiceCollection AddEmployeeModule(this IServiceCollection services) | |
=> services | |
.AddTransient<IEmployeeService, EmployeeService>() | |
; | |
} | |
} |
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 IoC.DI.WinForm.Sample.Forms; | |
using Microsoft.Extensions.DependencyInjection; | |
namespace IoC.DI.WinForm.Sample.Configuration | |
{ | |
public static class FormRegisterExtensions | |
{ | |
/// <summary> | |
/// Register your forms for IServiceProvider | |
/// </summary> | |
/// <param name="services"></param> | |
/// <returns></returns> | |
public static IServiceCollection AddFormModule(this IServiceCollection services) | |
=> services | |
.AddSingleton<Container>() | |
.AddTransient<SubForm>() | |
; | |
// CONTAINER IS PARENT MDI HOLDER SO MUST SINGLETON, CHILDS ARE MULTIPLE ON PROGRAM SO MUST TRANSIENT | |
} | |
} |
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 IoC.DI.WinForm.Sample | |
{ | |
internal static class Program | |
{ | |
/// <summary> | |
/// Single thread application WinForm limitations. | |
/// </summary> | |
[STAThread] | |
static void Main() | |
{ | |
var sw = Stopwatch.StartNew(); | |
// Set Visual Settings | |
Application.EnableVisualStyles(); | |
Application.SetCompatibleTextRenderingDefault(false); | |
SkinManager.EnableMdiFormSkins(); | |
SkinManager.EnableFormSkins(); | |
UserLookAndFeel.Default.SetSkinStyle("DevExpress Style"); | |
// Set Logger Settings | |
string fileFormatter = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"; | |
string consoleFormatter = "{Timestamp:HH:mm} [{Level}] ({ThreadId}) {Message}{NewLine}{Exception}"; | |
Logger logConfig = new LoggerConfiguration() | |
.WriteTo.File(restrictedToMinimumLevel: LogEventLevel.Warning, formatter: new CompactJsonFormatter(), path: "Logs\\Log.json", rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true, fileSizeLimitBytes: 100000000) // 100 MB | |
.WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information, outputTemplate: consoleFormatter) | |
.WriteTo.Udp(restrictedToMinimumLevel: LogEventLevel.Information, remoteAddress: "127.0.0.1", remotePort: 7071, family: AddressFamily.InterNetwork, outputTemplate: consoleFormatter) | |
.CreateLogger(); | |
Log.Logger = logConfig; | |
// WinForm Dependency Injection and IoC | |
IHost host = Host.CreateDefaultBuilder() | |
.ConfigureAppConfiguration((context, builder) => | |
{ | |
RegisterConfigs(builder); | |
}) | |
.ConfigureServices((context, services) => | |
{ | |
ConfigureServices(context.Configuration, services); | |
}) | |
.ConfigureLogging((logging) => | |
{ | |
ConfigureLogger(logging); | |
}) | |
.Build(); | |
IServiceProvider services = host.Services; | |
// GET CONTAINER FROM DEPENDENCY INJECTION: | |
Container container = services.GetRequiredService<Container>(); | |
sw.Stop(); | |
var timerResult = Convert.ToDecimal(sw.ElapsedMilliseconds / 1000); | |
Log.Information("WinForm DI Test Application Started!! Takes {timerResult} seconds to start!", timerResult); | |
Application.Run(container); | |
// What normally STA Thread apps do: | |
//Application.Run(new Container()); | |
} | |
/// <summary> | |
/// Configure and register logger service. | |
/// </summary> | |
/// <param name="logging"></param> | |
private static void ConfigureLogger(Microsoft.Extensions.Logging.ILoggingBuilder logging) | |
{ | |
logging.Services.AddSingleton<ILogger, Logger>(); | |
} | |
/// <summary> | |
/// Add config files, kestrels etc. | |
/// </summary> | |
/// <param name="builder"></param> | |
private static void RegisterConfigs(IConfigurationBuilder builder) | |
{ | |
builder.AddJsonFile("appsettings.json", true, true); | |
} | |
/// <summary> | |
/// Configure and register any services. | |
/// </summary> | |
/// <param name="configuration"></param> | |
/// <param name="services"></param> | |
private static void ConfigureServices(IConfiguration configuration, IServiceCollection services) | |
{ | |
// Map Configs | |
//services.Configure<TESTCONFIGOBJECT>(configuration.GetSection("User")); | |
RegisterHttpClientServices(); | |
// Register Services + Forms | |
services.AddServiceModules(); | |
} | |
private static void RegisterHttpClientServices(IConfiguration configuration, IServiceCollection services) | |
{ | |
// Create HTTP clients for all app. | |
//services.AddHttpClient(configuration.GetSection("ClientNames:HttpClientName").Value, options => | |
services.AddHttpClient("localhost", options => | |
{ | |
options.BaseAddress = new Uri("https://localhost:5000/api/"); | |
options.DefaultRequestHeaders.Accept.Clear(); | |
options.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); | |
//options.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", configuration.GetSection("AuthSettings:Token").Value); | |
options.Timeout = TimeSpan.FromMinutes(15); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment