Skip to content

Commit

Permalink
Add support for abstract class parameters in settings
Browse files Browse the repository at this point in the history
When a parameter is an abstract class, now accept the type name of a concrete subclass that has a default constructor ( the same way interfaces are supported)
  • Loading branch information
Thibaud DESODT authored and tsimbalar committed Nov 8, 2017
1 parent 9f27375 commit f19f196
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public static object ConvertToType(string value, Type toType)
if (convertor != null)
return convertor(value);

if (toTypeInfo.IsInterface && !string.IsNullOrWhiteSpace(value))
if ((toTypeInfo.IsInterface || toTypeInfo.IsAbstract) && !string.IsNullOrWhiteSpace(value))
{
var type = Type.GetType(value.Trim(), throwOnError: false);
if (type != null)
Expand Down
16 changes: 16 additions & 0 deletions test/Serilog.Tests/Settings/SettingValueConversionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Serilog.Formatting;
using Serilog.Formatting.Json;
using Serilog.Settings.KeyValuePairs;
using Serilog.Tests.Support;
using Xunit;

namespace Serilog.Tests.Settings
Expand Down Expand Up @@ -51,6 +52,21 @@ public void StringValuesConvertToDefaultInstancesIfTargetIsInterface()
Assert.IsType<JsonFormatter>(result);
}

[Fact]
public void StringValuesConvertToDefaultInstancesIfTargetIsAbstractClass()
{
var result = SettingValueConversions.ConvertToType("Serilog.Tests.Support.DummyConcreteClassWithDefaultConstructor, Serilog.Tests", typeof(DummyAbstractClass));
Assert.IsType<DummyConcreteClassWithDefaultConstructor>(result);
}

[Fact]
public void StringValuesThrowsWhenMissingDefaultConstructorIfTargetIsAbstractClass()
{
var value = "Serilog.Tests.Support.DummyConcreteClassWithoutDefaultConstructor, Serilog.Tests";
Assert.Throws<InvalidOperationException>(() =>
SettingValueConversions.ConvertToType(value, typeof(DummyAbstractClass)));
}

[Theory]
[InlineData("3.14:21:18.986", 3 /*days*/, 14 /*hours*/, 21 /*min*/, 18 /*sec*/, 986 /*ms*/)]
[InlineData("4", 4, 0, 0, 0, 0)] // minimal : days
Expand Down
23 changes: 23 additions & 0 deletions test/Serilog.Tests/Support/ClassHierarchy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
namespace Serilog.Tests.Support
{

public abstract class DummyAbstractClass
{
}

public class DummyConcreteClassWithDefaultConstructor
{
// ReSharper disable once UnusedParameter.Local
public DummyConcreteClassWithDefaultConstructor(string param = "")
{
}
}

public class DummyConcreteClassWithoutDefaultConstructor
{
// ReSharper disable once UnusedParameter.Local
public DummyConcreteClassWithoutDefaultConstructor(string param)
{
}
}
}

0 comments on commit f19f196

Please sign in to comment.