-
-
Notifications
You must be signed in to change notification settings - Fork 832
/
DependencyResolutionExceptionTests.cs
106 lines (88 loc) · 3.24 KB
/
DependencyResolutionExceptionTests.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
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Permissions;
using Autofac.Core;
using Xunit;
namespace Autofac.Test.Core
{
// ReSharper disable ClassNeverInstantiated.Local, UnusedParameter.Local
public class DependencyResolutionExceptionTests
{
public class A
{
public const string Message = "This is the original exception.";
public A()
{
throw new InvalidOperationException(Message);
}
}
public class B
{
public B(A a)
{
}
}
public class C
{
public C(B b)
{
}
}
[Fact]
public void ExceptionMessageUnwrapsNestedResolutionFailures()
{
var builder = new ContainerBuilder();
builder.RegisterType<A>();
builder.Register(c => new B(c.Resolve<A>()));
builder.RegisterType<C>();
Exception ex;
using (var container = builder.Build())
{
ex = Assert.Throws<DependencyResolutionException>(() => container.Resolve<C>());
}
var n = GetType().FullName;
Assert.Equal($"An exception was thrown while activating {n}+C -> λ:{n}+B -> {n}+A.", ex.Message);
var inner = ex.InnerException;
Assert.IsType<DependencyResolutionException>(inner);
Assert.Equal("An exception was thrown while invoking the constructor 'Void .ctor()' on type 'A'.", inner.Message);
Assert.IsType<InvalidOperationException>(inner.InnerException);
Assert.Equal(A.Message, inner.InnerException.Message);
}
[Serializable]
public class CustomDependencyResolutionException : DependencyResolutionException
{
public int Value { get; }
public CustomDependencyResolutionException(int value)
: base(null)
{
Value = value;
}
protected CustomDependencyResolutionException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info == null) throw new ArgumentNullException(nameof(info));
Value = info.GetInt32(nameof(Value));
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue(nameof(Value), 123);
}
}
[Fact]
public void SupportCustomRuntimeSerialization()
{
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, new CustomDependencyResolutionException(123));
stream.Position = 0;
var exception = (CustomDependencyResolutionException)formatter.Deserialize(stream);
Assert.Equal(123, exception.Value);
}
}
}
}