Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
DefaultImplementationAttribute.cs
1using System;
2using System.Collections.Generic;
3using System.Reflection;
4
6{
11 [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
12 public class DefaultImplementationAttribute : Attribute
13 {
14 private static readonly Dictionary<Type, Type> defaultImplementationOverrides = new Dictionary<Type, Type>();
15 private readonly Type type;
16
23 {
24 if (Type is null)
25 throw new ArgumentException("Type cannot be null.", nameof(Type));
26
27 this.type = Type;
28 }
29
33 public Type Type => this.type;
34
40 public static void RegisterDefaultImplementation(Type From, Type To)
41 {
42 lock (defaultImplementationOverrides)
43 {
44 if (defaultImplementationOverrides.ContainsKey(From))
45 throw new InvalidOperationException("Default implemnentation already registered.");
46
47 defaultImplementationOverrides[From] = To;
48 }
49 }
50
56 public static bool UnregisterDefaultImplementation(Type From, Type To)
57 {
58 lock (defaultImplementationOverrides)
59 {
60 if (defaultImplementationOverrides.TryGetValue(From, out Type To2) && To == To2)
61 return defaultImplementationOverrides.Remove(From);
62 else
63 return false;
64 }
65 }
66
73 public static bool TryGetDefaultImplementation(Type Type, out Type DefaultImplementation)
74 {
75 lock (defaultImplementationOverrides)
76 {
77 if (defaultImplementationOverrides.TryGetValue(Type, out DefaultImplementation))
78 return true;
79 }
80
81 TypeInfo TI = Type.GetTypeInfo();
82 DefaultImplementationAttribute Attr = TI.GetCustomAttribute<DefaultImplementationAttribute>(true);
83
84 if (!(Attr is null))
85 {
86 DefaultImplementation = Attr.Type;
87 return true;
88 }
89 else
90 return false;
91 }
92 }
93}
Defines a default implementation for an interface. If a request to instantiate an interface is made,...
static bool UnregisterDefaultImplementation(Type From, Type To)
Unregisters a default implementation for an interface.
static void RegisterDefaultImplementation(Type From, Type To)
Registers a default implementation for an interface.
DefaultImplementationAttribute(Type Type)
Defines a default implementation for an interface. If a request to instantiate an interface is made,...
static bool TryGetDefaultImplementation(Type Type, out Type DefaultImplementation)
Tries to get the default implementation for an interface.