- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathProgram.cs
63 lines (52 loc) · 1.75 KB
/
Program.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
varbuilder=WebApplication.CreateBuilder();
//Register all objects configured by classes that implements IBootstrap.
//This is useful when you have large amount of classes in your project that needs
//registration. You can register them near where they are (usually in the same folder) instead of
//registering them somewhere in a giant registration function
vartype=typeof(IBootstrap);
vartypes=System.AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x =>x.GetTypes())
.Where(p =>type.IsAssignableFrom(p)&&p.IsClass);
foreach(varpintypes)
{
varconfig=(IBootstrap)System.Activator.CreateInstance(p);
config.Register(builder.Services);
}
varapp=builder.Build();
app.Run(context =>
{
varperson=context.RequestServices.GetService<Person>();
vargreeting=context.RequestServices.GetService<Greeting>();
returncontext.Response.WriteAsync($"{greeting.Message}{person.Name}");
});
app.Run();
publicinterfaceIBootstrap
{
voidRegister(IServiceCollectionservices);
}
publicclassRegistration1:IBootstrap
{
publicvoidRegister(IServiceCollectionservices)
{
services.AddTransient(x =>newPerson{Name="Mahmoud"});
//continue registering all your classes here
}
}
//This is a contrite sample but it demonstrates that you can have these two registration classes in farflung folders near the classes
//they are registrating.
publicclassRegistration2:IBootstrap
{
publicvoidRegister(IServiceCollectionservices)
{
services.AddTransient(x =>newGreeting{Message="Good Morning"});
//continue registering all your classes here
}
}
publicclassPerson
{
publicstringName{get;set;}
}
publicclassGreeting
{
publicstringMessage{get;set;}
}