/
DefaultGrainActivator.cs
76 lines (66 loc) · 2.47 KB
/
DefaultGrainActivator.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
using System;
using System.Collections.Concurrent;
using System.Globalization;
using Microsoft.Extensions.DependencyInjection;
namespace Orleans.Runtime
{
/// <summary>
/// <see cref="IGrainActivator"/> that uses type activation to create grains.
/// </summary>
public class DefaultGrainActivator : IGrainActivator
{
private readonly ConstructorArgumentFactory argumentFactory;
private readonly ConcurrentDictionary<Type, ObjectFactory> typeActivatorCache;
/// <summary>
/// Public constructor
/// </summary>
/// <param name="serviceProvider"></param>
public DefaultGrainActivator(IServiceProvider serviceProvider)
{
this.argumentFactory = new ConstructorArgumentFactory(serviceProvider);
this.typeActivatorCache = new ConcurrentDictionary<Type, ObjectFactory>();
}
/// <inheritdoc />
public virtual object Create(IGrainActivationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var grainType = context.GrainType;
if (grainType == null)
{
throw new ArgumentException(
string.Format(
CultureInfo.InvariantCulture, "The '{0}' property of '{1}' must not be null.",
nameof(context.GrainType),
nameof(IGrainActivationContext)));
}
var serviceProvider = context.ActivationServices;
var activator = this.typeActivatorCache.GetOrAdd(grainType, this.CreateFactory);
var grain = activator(serviceProvider, this.argumentFactory.CreateArguments(context));
return grain;
}
/// <inheritdoc />
public virtual void Release(IGrainActivationContext context, object grain)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (grain == null)
{
throw new ArgumentNullException(nameof(grain));
}
var disposable = grain as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
private ObjectFactory CreateFactory(Type type)
{
return ActivatorUtilities.CreateFactory(type, this.argumentFactory.ArgumentTypes(type));
}
}
}