Use ActivatorUtlities.CreateFactory instead of CreateInstance (#1643)

* Use ActivatorUtlities.CreateFactory instead of CreateInstance
- Turns out CreateFactory is much much faster
- Added a benchmark for hub activation
This commit is contained in:
David Fowler 2018-03-19 00:19:54 -07:00 committed by GitHub
parent d4d5a08bc2
commit cf7c8629ff
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 1 deletions

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Text;
using BenchmarkDotNet.Attributes;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.SignalR.Microbenchmarks
{
public class DefaultHubActivatorBenchmark
{
private DefaultHubActivator<MyHub> _activator;
[GlobalSetup]
public void GlobalSetup()
{
var services = new ServiceCollection();
_activator = new DefaultHubActivator<MyHub>(services.BuildServiceProvider());
}
[Benchmark]
public int Create()
{
var hub = _activator.Create();
int result = hub.Addition();
return result;
}
public class MyHub : Hub
{
public int Addition()
{
return 1 + 1;
}
}
}
}

View File

@ -9,6 +9,8 @@ namespace Microsoft.AspNetCore.SignalR
{
public class DefaultHubActivator<THub> : IHubActivator<THub> where THub: Hub
{
// Object factory for THub instances
private static readonly Lazy<ObjectFactory> _objectFactory = new Lazy<ObjectFactory>(() => ActivatorUtilities.CreateFactory(typeof(THub), Type.EmptyTypes));
private readonly IServiceProvider _serviceProvider;
private bool? _created;
@ -25,7 +27,7 @@ namespace Microsoft.AspNetCore.SignalR
var hub = _serviceProvider.GetService<THub>();
if (hub == null)
{
hub = ActivatorUtilities.CreateInstance<THub>(_serviceProvider);
hub = (THub)_objectFactory.Value(_serviceProvider, Array.Empty<object>());
_created = true;
}