-
Notifications
You must be signed in to change notification settings - Fork 57
/
CommerceControllerActivator.cs
65 lines (51 loc) · 2.27 KB
/
CommerceControllerActivator.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
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Ploeh.Samples.Commerce.Domain;
using Ploeh.Samples.Commerce.SqlDataAccess;
using Ploeh.Samples.Commerce.Web.Controllers;
namespace Ploeh.Samples.Commerce.Web
{
public class CommerceControllerActivator : IControllerActivator
{
private readonly CommerceConfiguration configuration;
// Singletons
private readonly IUserContext userContext;
public CommerceControllerActivator(CommerceConfiguration configuration)
{
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
this.configuration = configuration;
// Create singletons
this.userContext = new AspNetUserContextAdapter();
}
public object Create(ControllerContext context) =>
this.Create(context.ActionDescriptor.ControllerTypeInfo.AsType());
public void Release(ControllerContext context, object controller) =>
(controller as IDisposable)?.Dispose();
public Controller Create(Type type)
{
// Create Scoped components
var context = new CommerceContext(this.configuration.ConnectionString);
// Create Transient components
switch (type.Name)
{
case nameof(HomeController):
return new HomeController(
new ProductService(
this.CreateProductRepository(context),
this.userContext));
//case nameof(AccountController):
// return new AccountController(...);
//case nameof(UserController):
// return new UserController(...)
//case nameof(LoginController):
// return new LoginController(...);
default: throw new InvalidOperationException($"Unknown controller {type}.");
}
}
// --- Start code Listing 5.16 ----
private IProductRepository CreateProductRepository(CommerceContext context) =>
(IProductRepository)Activator.CreateInstance(this.configuration.ProductRepositoryType, context);
// --- End code Listing 5.16 ----
}
}