-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDemo.cs
485 lines (345 loc) · 17.6 KB
/
Demo.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Castle.Windsor;
using Castle.MicroKernel.Registration;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.FeatureManagement;
using Microsoft.FeatureManagement.FeatureFilters;
using Ninject;
using System.Reflection;
using Unity;
using SimpleInjector;
namespace DIContainers
{
public static class Demo
{
public static void ResolveMultipleImplementationsWithMEDI()
{
Console.WriteLine("========== Demo: Resolve multiple implementations with MEDI ==========");
var services = new ServiceCollection();
services.AddTransient<IStrategy, StrategyA>();
services.AddTransient<IStrategy, StrategyB>();
services.AddSingleton<IApplication, DemoAppWithMEDI>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
IApplication app = serviceProvider.GetRequiredService<IApplication>();
//
// StrategyB will also be initialized.
app.RunStrategy("StrategyA");
//
// Although StrategyA is registered as transient, the second call will still use the same instance.
app.RunStrategy("StrategyA");
}
public static void InjectPropertyWithMEDI()
{
Console.WriteLine("========== Demo: Inject property with MEDI ==========");
var services = new ServiceCollection();
services.AddSingleton<IMyLogger, MyLogger>();
services.AddSingleton(sp => new ComponentA()
{
Logger = sp.GetRequiredService<IMyLogger>()
});
services.AddSingleton(sp => new ComponentB()
{
Logger = sp.GetRequiredService<IMyLogger>()
});
services.AddSingleton<IApplication>(sp => new DemoAppWithMEDI(
sp.GetRequiredService<IEnumerable<IStrategy>>())
{
A = sp.GetRequiredService<ComponentA>(),
B = sp.GetRequiredService<ComponentB>()
});
ServiceProvider serviceProvider = services.BuildServiceProvider();
IApplication app = serviceProvider.GetRequiredService<IApplication>();
app.A.DoSomething();
app.A.Logger.Info("BaseComponent A of the App with MEDI is doing something.");
app.B.DoSomething();
app.B.Logger.Info("BaseComponent B of the App with MEDI is doing something.");
}
public static void ResolveMultipleImplementationsWithAutofac()
{
Console.WriteLine("========== Demo: Resolve multiple implementations with Autofac ==========");
var builder = new ContainerBuilder();
builder.RegisterType<StrategyA>().Keyed<IStrategy>("StrategyA");
builder.RegisterType<StrategyB>().Keyed<IStrategy>("StrategyB");
builder.RegisterType<DemoAppWithAutofac>().As<IApplication>().SingleInstance();
var container = builder.Build();
var app = container.Resolve<IApplication>();
//
// StrategyB will not be initialized
app.RunStrategy("StrategyA");
//
// A new instance will be initialized since StrategyA is transient.
app.RunStrategy("StrategyA");
}
public static void InjectPropertyWithAutofac()
{
Console.WriteLine("========== Demo: Inject property with Autofac ==========");
var builder = new ContainerBuilder();
builder.RegisterType<MyLogger>().As<IMyLogger>().SingleInstance();
builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(BaseComponent)))
.Where(type => type.IsSubclassOf(typeof(BaseComponent)))
.PropertiesAutowired()
.AsSelf()
.SingleInstance();
builder.RegisterType<DemoAppWithAutofac>()
.PropertiesAutowired()
.As<IApplication>()
.SingleInstance();
var container = builder.Build();
var app = container.Resolve<IApplication>();
app.A.DoSomething();
app.A.Logger.Info("BaseComponent A of the App with Autofac is doing something.");
app.B.DoSomething();
app.B.Logger.Info("BaseComponent B of the App with Autofac is doing something.");
}
public static async void UseFeatureManagementWithAutofac()
{
Console.WriteLine("========== Demo: Use Microsoft.FeatureManagement with Autofac ==========");
IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var builder = new ContainerBuilder();
builder.RegisterInstance(config).SingleInstance();
builder.RegisterType<ConfigurationFeatureDefinitionProvider>().As<IFeatureDefinitionProvider>();
builder.RegisterInstance(new FeatureManagementOptions()).SingleInstance();
builder.RegisterInstance(LoggerFactory.Create(builder => builder.AddConsole()))
.As<ILoggerFactory>().SingleInstance();
builder.Register(c => new FeatureManager(
c.Resolve<IFeatureDefinitionProvider>(),
c.Resolve<FeatureManagementOptions>())
{
FeatureFilters = c.Resolve<IEnumerable<IFeatureFilterMetadata>>(),
Logger = c.Resolve<ILoggerFactory>().CreateLogger<FeatureManager>()
}).As<IFeatureManager>()
.SingleInstance();
builder.RegisterInstance(Options.Create(new TargetingEvaluationOptions()))
.As<IOptions<TargetingEvaluationOptions>>()
.SingleInstance();
var targetingContextAccessor = new OnDemandTargetingContextAccessor();
builder.RegisterInstance(targetingContextAccessor)
.As<ITargetingContextAccessor>()
.SingleInstance();
builder.RegisterType<TargetingFilter>()
.As<IFeatureFilterMetadata>()
.SingleInstance();
var container = builder.Build();
IFeatureManager featureManager = container.Resolve<IFeatureManager>();
var users = new List<string>()
{
"Jeff",
"Sam"
};
const string feature = "Beta";
foreach (var user in users)
{
targetingContextAccessor.Current = new TargetingContext
{
UserId = user
};
Console.WriteLine($"{feature} is {(await featureManager.IsEnabledAsync(feature) ? "enabled" : "disabled")} for {user}.");
}
}
public static async void UseFeatureManagementWithAutofacPopulate()
{
Console.WriteLine("========== Demo: Use Microsoft.FeatureManagement with Autofac ==========");
IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
IServiceCollection services = new ServiceCollection();
var targetingContextAccessor = new OnDemandTargetingContextAccessor();
services.AddSingleton(config)
.AddSingleton<ITargetingContextAccessor>(targetingContextAccessor)
.AddFeatureManagement()
.AddFeatureFilter<TargetingFilter>();
var builder = new ContainerBuilder();
builder.Populate(services);
var container = builder.Build();
IFeatureManager featureManager = container.Resolve<IFeatureManager>();
var users = new List<string>()
{
"Jeff",
"Sam"
};
const string feature = "Beta";
foreach (var user in users)
{
targetingContextAccessor.Current = new TargetingContext
{
UserId = user
};
Console.WriteLine($"{feature} is {(await featureManager.IsEnabledAsync(feature) ? "enabled" : "disabled")} for {user}.");
}
}
public static async void UseFeatureManagementWithUnity()
{
Console.WriteLine("========== Demo: Use Microsoft.FeatureManagement with Unity ==========");
IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var container = new UnityContainer();
container.RegisterInstance(config, InstanceLifetime.Singleton);
container.RegisterType<IFeatureDefinitionProvider, ConfigurationFeatureDefinitionProvider>(TypeLifetime.Singleton);
container.RegisterInstance(new FeatureManagementOptions(), InstanceLifetime.Singleton);
container.RegisterInstance(LoggerFactory.Create(builder => builder.AddConsole()), InstanceLifetime.Singleton);
container.RegisterFactory<IFeatureManager>(f => new FeatureManager(
f.Resolve<IFeatureDefinitionProvider>(),
f.Resolve<FeatureManagementOptions>())
{
FeatureFilters = f.ResolveAll<IFeatureFilterMetadata>(),
Logger = f.Resolve<ILoggerFactory>().CreateLogger<FeatureManager>(),
}, FactoryLifetime.Singleton);
container.RegisterInstance(Options.Create(new TargetingEvaluationOptions()), InstanceLifetime.Singleton);
var targetingContextAccessor = new OnDemandTargetingContextAccessor();
container.RegisterInstance<ITargetingContextAccessor>(targetingContextAccessor, InstanceLifetime.Singleton);
container.RegisterType<IFeatureFilterMetadata, TargetingFilter>("Targeting", TypeLifetime.Singleton);
IFeatureManager featureManager = container.Resolve<IFeatureManager>();
var users = new List<string>()
{
"Jeff",
"Sam"
};
const string feature = "Beta";
foreach (var user in users)
{
targetingContextAccessor.Current = new TargetingContext
{
UserId = user
};
Console.WriteLine($"{feature} is {(await featureManager.IsEnabledAsync(feature) ? "enabled" : "disabled")} for {user}.");
}
}
public static async void UseFeatureManagementWithCastleWindsor()
{
Console.WriteLine("========== Demo: Use Microsoft.FeatureManagement with Castle.Windsor ==========");
IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var container = new WindsorContainer();
container.Register(Component.For<IConfiguration>()
.Instance(config)
.LifestyleSingleton());
container.Register(Component.For<IFeatureDefinitionProvider>()
.ImplementedBy<ConfigurationFeatureDefinitionProvider>()
.LifestyleSingleton());
container.Register(Component.For<FeatureManagementOptions>()
.Instance(new FeatureManagementOptions())
.LifestyleSingleton());
container.Register(Component.For<ILoggerFactory>()
.Instance(LoggerFactory.Create(builder => builder.AddConsole()))
.LifestyleSingleton());
container.Register(Component.For<IFeatureManager>().UsingFactoryMethod(kernel => new FeatureManager(
kernel.Resolve<IFeatureDefinitionProvider>(),
kernel.Resolve<FeatureManagementOptions>())
{
FeatureFilters = kernel.ResolveAll<IFeatureFilterMetadata>(),
Logger = kernel.Resolve<ILoggerFactory>().CreateLogger<FeatureManager>()
}));
container.Register(Component.For<IOptions<TargetingEvaluationOptions>>()
.Instance(Options.Create(new TargetingEvaluationOptions()))
.LifestyleSingleton());
var targetingContextAccessor = new OnDemandTargetingContextAccessor();
container.Register(Component.For<ITargetingContextAccessor>()
.Instance(targetingContextAccessor)
.LifestyleSingleton());
container.Register(Component.For<IFeatureFilterMetadata>()
.ImplementedBy<TargetingFilter>()
.LifestyleSingleton());
IFeatureManager featureManager = container.Resolve<IFeatureManager>();
var users = new List<string>()
{
"Jeff",
"Sam"
};
const string feature = "Beta";
foreach (var user in users)
{
targetingContextAccessor.Current = new TargetingContext
{
UserId = user
};
Console.WriteLine($"{feature} is {(await featureManager.IsEnabledAsync(feature) ? "enabled" : "disabled")} for {user}.");
}
}
public static async void UseFeatureManagementWithSimpleInjector()
{
Console.WriteLine("========== Demo: Use Microsoft.FeatureManagement with SimpleInjector ==========");
IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var container = new Container();
container.RegisterSingleton(typeof(IConfiguration), () => config);
container.RegisterSingleton<IFeatureDefinitionProvider, ConfigurationFeatureDefinitionProvider>();
container.RegisterSingleton(typeof(FeatureManagementOptions), () => new FeatureManagementOptions());
container.RegisterSingleton(typeof(ILoggerFactory), () => LoggerFactory.Create(builder => builder.AddConsole()));
container.RegisterSingleton(typeof(IFeatureManager), () => new FeatureManager(
container.GetInstance<IFeatureDefinitionProvider>(),
container.GetInstance<FeatureManagementOptions>())
{
FeatureFilters = container.GetAllInstances<IFeatureFilterMetadata>(),
Logger = container.GetInstance<ILoggerFactory>().CreateLogger<FeatureManager>()
});
container.RegisterSingleton(typeof(IOptions<TargetingEvaluationOptions>), () => Options.Create(new TargetingEvaluationOptions()));
var targetingContextAccessor = new OnDemandTargetingContextAccessor();
container.RegisterSingleton(typeof(ITargetingContextAccessor), () => targetingContextAccessor);
container.Collection.Append<IFeatureFilterMetadata, TargetingFilter>(Lifestyle.Singleton);
IFeatureManager featureManager = container.GetInstance<IFeatureManager>();
var users = new List<string>()
{
"Jeff",
"Sam"
};
const string feature = "Beta";
foreach (var user in users)
{
targetingContextAccessor.Current = new TargetingContext
{
UserId = user
};
Console.WriteLine($"{feature} is {(await featureManager.IsEnabledAsync(feature) ? "enabled" : "disabled")} for {user}.");
}
}
public static async void UseFeatureManagementWithNinject()
{
Console.WriteLine("========== Demo: Use Microsoft.FeatureManagement with Ninject ==========");
IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var kernel = new StandardKernel();
kernel.Bind<IConfiguration>()
.ToConstant(config)
.InSingletonScope();
kernel.Bind<IFeatureDefinitionProvider>()
.To<ConfigurationFeatureDefinitionProvider>()
.InSingletonScope();
kernel.Bind<FeatureManagementOptions>()
.ToConstant(new FeatureManagementOptions())
.InSingletonScope();
kernel.Bind<ILoggerFactory>()
.ToConstant(LoggerFactory.Create(builder => builder.AddConsole()))
.InSingletonScope();
kernel.Bind<IFeatureManager>().ToMethod(c => new FeatureManager(
c.Kernel.Get<IFeatureDefinitionProvider>(),
c.Kernel.Get<FeatureManagementOptions>())
{
FeatureFilters = c.Kernel.Get<IEnumerable<IFeatureFilterMetadata>>(),
Logger = c.Kernel.Get<ILoggerFactory>().CreateLogger<FeatureManager>()
}).InSingletonScope();
kernel.Bind<IOptions<TargetingEvaluationOptions>>()
.ToConstant(Options.Create(new TargetingEvaluationOptions()))
.InSingletonScope();
var targetingContextAccessor = new OnDemandTargetingContextAccessor();
kernel.Bind<ITargetingContextAccessor>()
.ToConstant(targetingContextAccessor)
.InSingletonScope();
kernel.Bind<IFeatureFilterMetadata>()
.To<TargetingFilter>()
.InSingletonScope();
IFeatureManager featureManager = kernel.Get<IFeatureManager>();
var users = new List<string>()
{
"Jeff",
"Sam"
};
const string feature = "Beta";
foreach (var user in users)
{
targetingContextAccessor.Current = new TargetingContext
{
UserId = user
};
Console.WriteLine($"{feature} is {(await featureManager.IsEnabledAsync(feature) ? "enabled" : "disabled")} for {user}.");
}
}
}
}