Line data Source code
1 : using System;
2 : using System.Reflection;
3 : using cdmdotnet.Logging;
4 : using Cqrs.Configuration;
5 : using Cqrs.Domain.Exceptions;
6 :
7 : namespace Cqrs.Domain.Factories
8 : {
9 : public class AggregateFactory : IAggregateFactory
10 0 : {
11 : protected IDependencyResolver DependencyResolver { get; private set; }
12 :
13 : protected ILogger Logger { get; private set; }
14 :
15 0 : public AggregateFactory(IDependencyResolver dependencyResolver, ILogger logger)
16 : {
17 : DependencyResolver = dependencyResolver;
18 : Logger = logger;
19 : }
20 :
21 0 : public virtual TAggregate CreateAggregate<TAggregate>(Guid? rsn = null, bool tryDependencyResolutionFirst = true)
22 : {
23 : return (TAggregate)CreateAggregate(typeof (TAggregate), rsn);
24 : }
25 :
26 0 : public object CreateAggregate(Type aggregateType, Guid? rsn = null, bool tryDependencyResolutionFirst = true)
27 : {
28 : if (tryDependencyResolutionFirst)
29 : {
30 : try
31 : {
32 : return DependencyResolver.Resolve(aggregateType);
33 : }
34 : catch
35 : {
36 : Logger.LogDebug(string.Format("Using the dependency resolver to create an instance of the aggregate typed '{0}' failed.", aggregateType.FullName), "Cqrs.Domain.Factories.AggregateFactory.CreateAggregate");
37 : }
38 : }
39 :
40 : try
41 : {
42 : return Activator.CreateInstance(aggregateType, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null, new object[] { DependencyResolver, Logger, rsn }, null);
43 : }
44 : catch (MissingMethodException exception)
45 : {
46 : Logger.LogDebug(string.Format("Looking for a private constructor with a dependency resolver and logger, to create an instance of the aggregate typed '{0}' failed.", aggregateType.FullName), "Cqrs.Domain.Factories.AggregateFactory.CreateAggregate", exception);
47 : try
48 : {
49 : return Activator.CreateInstance(aggregateType, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, new object[] { DependencyResolver, Logger }, null);
50 : }
51 : catch (MissingMethodException exception2)
52 : {
53 : Logger.LogDebug(string.Format("Looking for a private constructor with a dependency resolver and logger, to create an instance of the aggregate typed '{0}' failed.", aggregateType.FullName), "Cqrs.Domain.Factories.AggregateFactory.CreateAggregate", exception2);
54 : try
55 : {
56 : return Activator.CreateInstance(aggregateType, true);
57 : }
58 : catch (MissingMethodException)
59 : {
60 : throw new MissingParameterLessConstructorException(aggregateType);
61 : }
62 : }
63 : }
64 : }
65 : }
66 : }
|