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:
parent
d4d5a08bc2
commit
cf7c8629ff
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue