forked from pszmyd/SignalR.Autofac
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AutofacDependencyResolver.cs
83 lines (73 loc) · 2.33 KB
/
AutofacDependencyResolver.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
using System;
using System.Collections.Generic;
using System.Linq;
using Autofac.Core;
using Autofac.Core.Activators.ProvidedInstance;
using Autofac.Core.Lifetime;
using Autofac.Core.Registration;
namespace SignalR.Autofac
{
using global::Autofac;
/// <summary>
/// SingalR dependency resolver using Autofac container as backend.
/// </summary>
public class AutofacDependencyResolver : DefaultDependencyResolver, IRegistrationSource
{
private readonly ILifetimeScope _lifetimeScope;
public AutofacDependencyResolver(ILifetimeScope lifetimeScope)
{
_lifetimeScope = lifetimeScope;
_lifetimeScope.ComponentRegistry.AddRegistrationSource(this);
}
public override object GetService(Type serviceType)
{
object result;
_lifetimeScope.TryResolve(serviceType, out result);
return result;
}
public override IEnumerable<object> GetServices(Type serviceType)
{
object result;
_lifetimeScope.TryResolve(typeof(IEnumerable<>).MakeGenericType(serviceType), out result);
return (IEnumerable<object>)result;
}
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
{
var result = new IComponentRegistration[] { };
var typedService = service as TypedService;
if (typedService != null)
{
object instance;
var serviceType = typedService.ServiceType;
if (serviceType.IsGenericType && serviceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
serviceType = serviceType.GetGenericArguments()[0];
instance = base.GetServices(serviceType);
}
else
{
instance = base.GetService(serviceType);
}
if (instance != null)
{
result = new IComponentRegistration[]
{
new ComponentRegistration(
Guid.NewGuid(),
new ProvidedInstanceActivator(instance),
new CurrentScopeLifetime(),
InstanceSharing.Shared,
InstanceOwnership.ExternallyOwned,
new[] {service},
new Dictionary<string, object>())
};
}
}
return result;
}
bool IRegistrationSource.IsAdapterForIndividualComponents
{
get { return false; }
}
}
}