Introducing a general-purpose dependency injector to use `System` code from within...
[mono-project.git] / mcs / class / corlib / Mono / DependencyInjector.cs
blob117196aa6b159dba7cff4d24a335db1176ce322c
1 //
2 // DependencyInjector.cs
3 //
4 // Author:
5 // Martin Baulig <mabaul@microsoft.com>
6 //
7 // Copyright (c) 2018 Xamarin, Inc.
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining a copy
10 // of this software and associated documentation files (the "Software"), to deal
11 // in the Software without restriction, including without limitation the rights
12 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 // copies of the Software, and to permit persons to whom the Software is
14 // furnished to do so, subject to the following conditions:
16 // The above copyright notice and this permission notice shall be included in
17 // all copies or substantial portions of the Software.
19 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 // THE SOFTWARE.
26 using System;
27 #if !MOBILE
28 using System.Reflection;
29 #endif
31 namespace Mono
33 static class DependencyInjector
36 * Allows us to use code from `System.dll` in `mscorlib.dll`.
39 internal static ISystemDependencyProvider SystemProvider {
40 get {
41 lock (locker) {
42 if (systemDependency != null)
43 return systemDependency;
45 #if !MOBILE
46 // On Mobile, we initializes this during system startup.
47 systemDependency = ReflectionLoad ();
48 #endif
49 if (systemDependency == null)
50 throw new PlatformNotSupportedException ("Cannot get `ISystemDependencyProvider`.");
52 return systemDependency;
57 internal static void Register (ISystemDependencyProvider provider)
59 lock (locker) {
60 if (systemDependency != null && systemDependency != provider)
61 throw new InvalidOperationException ();
62 systemDependency = provider;
66 #if !MOBILE
67 static ISystemDependencyProvider ReflectionLoad ()
69 var type = Type.GetType ("Mono.SystemDependencyProvider, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
70 if (type == null)
71 return null;
73 var prop = type.GetProperty ("Instance", BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public);
74 if (prop == null)
75 return null;
77 return (ISystemDependencyProvider)prop.GetValue (null);
79 #endif
81 static object locker = new object ();
82 static ISystemDependencyProvider systemDependency;