├── LazyProxy.Sample ├── LazyProxy.Sample.csproj ├── Services.cs └── Program.cs ├── LazyProxy ├── LazyProxyBase.cs ├── LazyProxyImplementation.cs ├── LazyProxy.csproj └── LazyProxyBuilder.cs ├── LICENSE ├── LazyProxy.Tests ├── LazyProxy.Tests.csproj ├── DisposableLazyTests.cs └── LazyProxyBuilderTests.cs ├── LazyProxy.sln ├── README.md └── .gitignore /LazyProxy.Sample/LazyProxy.Sample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | Exe 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /LazyProxy.Sample/Services.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace LazyProxy.Sample 4 | { 5 | public interface IMyService 6 | { 7 | void Foo(); 8 | } 9 | 10 | public class MyService : IMyService 11 | { 12 | public MyService() => Console.WriteLine("Ctor"); 13 | public void Foo() => Console.WriteLine("Foo"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /LazyProxy/LazyProxyBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace LazyProxy 4 | { 5 | /// 6 | /// Base class for lazy proxies. 7 | /// 8 | public abstract class LazyProxyBase 9 | { 10 | /// 11 | /// Initializes inner instance with the valueFactory provided. 12 | /// 13 | /// Function that returns a value. 14 | protected internal abstract void Initialize(Func valueFactory); 15 | } 16 | } -------------------------------------------------------------------------------- /LazyProxy.Sample/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace LazyProxy.Sample 4 | { 5 | internal class Program 6 | { 7 | public static void Main(string[] args) 8 | { 9 | var lazyProxy = LazyProxyBuilder.CreateInstance(() => 10 | { 11 | Console.WriteLine("Creating an instance of the real service..."); 12 | return new MyService(); 13 | }); 14 | 15 | Console.WriteLine("Executing the 'Foo' method..."); 16 | lazyProxy.Foo(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2018 ServiceTitan, Inc. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. -------------------------------------------------------------------------------- /LazyProxy.Tests/LazyProxy.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | netcoreapp3.1 4 | false 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /LazyProxy/LazyProxyImplementation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace LazyProxy 4 | { 5 | /// 6 | /// This type hosts methods being used by lazy proxy implementations. 7 | /// 8 | public static class LazyProxyImplementation 9 | { 10 | /// 11 | /// Creates an instance of . 12 | /// 13 | /// Function that returns a value. 14 | /// Type of lazy value. 15 | /// Instance of 16 | public static Lazy CreateInstance(Func valueFactory) 17 | { 18 | return new Lazy(() => (T) valueFactory()); 19 | } 20 | 21 | /// 22 | /// Disposes an instance owned by if any. 23 | /// 24 | /// object. 25 | /// Type of lazy value. It must implement interface. 26 | public static void DisposeInstance(Lazy instanceOwner) 27 | where T: IDisposable 28 | { 29 | if (instanceOwner.IsValueCreated) 30 | { 31 | instanceOwner.Value.Dispose(); 32 | } 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /LazyProxy/LazyProxy.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | netstandard2.0 4 | 1.0.2 5 | LazyProxy 6 | Dynamic Lazy Proxy 7 | ServiceTitan, Inc. 8 | ServiceTitan, Inc. 9 | Copyright ServiceTitan, Inc. 10 | https://github.com/servicetitan/lazy-proxy 11 | https://github.com/servicetitan/lazy-proxy/blob/master/LICENSE 12 | https://github.com/servicetitan/lazy-proxy 13 | git 14 | lazy proxy dynamic runtime wrapper 15 | A dynamic lazy proxy is a class built in real time, that implemenets some interface T, takes to the constructor an argument Lazy of T and routes all invocations to the corresponding method or property of this argument. 16 | The real instance wrapped by Lazy of T is created only after the first invocation of method or property. It allows to distribute the loading from the class creation to the method or property invocation. 17 | true 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /LazyProxy.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LazyProxy", "LazyProxy\LazyProxy.csproj", "{4D46F079-C9C1-47AC-8A75-B89DCFDFFE07}" 4 | EndProject 5 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LazyProxy.Sample", "LazyProxy.Sample\LazyProxy.Sample.csproj", "{3C038BA1-52B1-4C0A-B7CD-DDE48287EE74}" 6 | EndProject 7 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LazyProxy.Tests", "LazyProxy.Tests\LazyProxy.Tests.csproj", "{A99EBCD2-140E-4A72-AA3F-DC018B2F3F7D}" 8 | EndProject 9 | Global 10 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 11 | Debug|Any CPU = Debug|Any CPU 12 | Release|Any CPU = Release|Any CPU 13 | EndGlobalSection 14 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 15 | {4D46F079-C9C1-47AC-8A75-B89DCFDFFE07}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 16 | {4D46F079-C9C1-47AC-8A75-B89DCFDFFE07}.Debug|Any CPU.Build.0 = Debug|Any CPU 17 | {4D46F079-C9C1-47AC-8A75-B89DCFDFFE07}.Release|Any CPU.ActiveCfg = Release|Any CPU 18 | {4D46F079-C9C1-47AC-8A75-B89DCFDFFE07}.Release|Any CPU.Build.0 = Release|Any CPU 19 | {3C038BA1-52B1-4C0A-B7CD-DDE48287EE74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 20 | {3C038BA1-52B1-4C0A-B7CD-DDE48287EE74}.Debug|Any CPU.Build.0 = Debug|Any CPU 21 | {3C038BA1-52B1-4C0A-B7CD-DDE48287EE74}.Release|Any CPU.ActiveCfg = Release|Any CPU 22 | {3C038BA1-52B1-4C0A-B7CD-DDE48287EE74}.Release|Any CPU.Build.0 = Release|Any CPU 23 | {A99EBCD2-140E-4A72-AA3F-DC018B2F3F7D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {A99EBCD2-140E-4A72-AA3F-DC018B2F3F7D}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {A99EBCD2-140E-4A72-AA3F-DC018B2F3F7D}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {A99EBCD2-140E-4A72-AA3F-DC018B2F3F7D}.Release|Any CPU.Build.0 = Release|Any CPU 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /LazyProxy.Tests/DisposableLazyTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Moq; 3 | using Xunit; 4 | 5 | namespace LazyProxy.Tests 6 | { 7 | public class DisposableLazyTests 8 | { 9 | public interface IHaveDisposeBusinessMethod 10 | { 11 | void Dispose(); 12 | } 13 | 14 | public interface IImplementIDisposable: IDisposable 15 | { 16 | void DoSomething(); 17 | } 18 | 19 | [Fact] 20 | public void BusinessDisposeMethodIsCalled() 21 | { 22 | var mock = new Mock(MockBehavior.Strict); 23 | mock.Setup(s => s.Dispose()).Verifiable(); 24 | 25 | var proxy = LazyProxyBuilder.CreateInstance(() => mock.Object); 26 | 27 | proxy.Dispose(); 28 | 29 | mock.Verify(s => s.Dispose()); 30 | } 31 | 32 | [Fact] 33 | public void RegularDisposeMethodIsCalledIfInstanceIsCreated() 34 | { 35 | var mock = new Mock(MockBehavior.Strict); 36 | mock.Setup(s => s.DoSomething()); 37 | mock.Setup(s => s.Dispose()).Verifiable(); 38 | 39 | var proxy = LazyProxyBuilder.CreateInstance(() => mock.Object); 40 | 41 | proxy.DoSomething(); 42 | proxy.Dispose(); 43 | 44 | mock.Verify(s => s.Dispose()); 45 | } 46 | 47 | [Fact] 48 | public void RegularDisposeMethodIsNotCalledIfNoInstanceIsCreated() 49 | { 50 | var mock = new Mock(MockBehavior.Strict); 51 | var callCounter = 0; 52 | mock.Setup(s => s.Dispose()).Callback(() => callCounter++); 53 | 54 | var proxy = LazyProxyBuilder.CreateInstance(() => mock.Object); 55 | 56 | proxy.Dispose(); 57 | 58 | Assert.Equal(0, callCounter); 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LazyProxy 2 | 3 | `LazyProxy` is a lightweight library allowing to build a lazy proxy type for some interface `T` at runtime. The proxy type implements this interface and is initialized by the `Lazy` argument. All method and property invocations route to the corresponding members of the lazy's `Value`. 4 | 5 | For illustration, assume there is the following interface: 6 | 7 | ```CSharp 8 | public interface IMyService 9 | { 10 | void Foo(); 11 | } 12 | ``` 13 | 14 | Then the generated lazy proxy type looks like this: 15 | 16 | ```CSharp 17 | // In reality, the implementation is a little more complicated, 18 | // but the details are omitted for ease of understanding. 19 | public class LazyProxyImpl_IMyService : IMyService 20 | { 21 | private Lazy _service; 22 | 23 | public LazyProxyImpl_IMyService(Lazy service) 24 | { 25 | _service = service; 26 | } 27 | 28 | public void Foo() => _service.Value.Foo(); 29 | } 30 | ``` 31 | 32 | ## Get Packages 33 | 34 | The library provides in NuGet. 35 | 36 | ``` 37 | Install-Package LazyProxy 38 | ``` 39 | 40 | ## Get Started 41 | 42 | Consider the following service: 43 | 44 | ```CSharp 45 | public interface IMyService 46 | { 47 | void Foo(); 48 | } 49 | 50 | public class MyService : IMyService 51 | { 52 | public MyService() => Console.WriteLine("Ctor"); 53 | public void Foo() => Console.WriteLine("Foo"); 54 | } 55 | ``` 56 | 57 | A lazy proxy instance for this service can be created like this: 58 | 59 | ```CSharp 60 | var lazyProxy = LazyProxyBuilder.CreateInstance(() => 61 | { 62 | Console.WriteLine("Creating an instance of the real service..."); 63 | return new MyService(); 64 | }); 65 | 66 | Console.WriteLine("Executing the 'Foo' method..."); 67 | lazyProxy.Foo(); 68 | ``` 69 | 70 | The output for this example: 71 | 72 | ``` 73 | Executing the 'Foo' method... 74 | Creating an instance of the real service... 75 | Ctor 76 | Foo 77 | ``` 78 | 79 | ## Features 80 | 81 | Currently, `LazyProxy` supports the following: 82 | - Void/Result methods; 83 | - Async methods; 84 | - Generic methods; 85 | - Generic interfaces; 86 | - Ref/Out parameters; 87 | - Parameters with default values; 88 | - Parent interface members; 89 | - Indexers; 90 | - Properties (getters and setters); 91 | - Thread-safe proxy generation. 92 | 93 | **Not supported yet:** 94 | - Events 95 | 96 | ## Lazy Dependency Injection 97 | 98 | Lazy proxies can be used for IoC containers to improve performance by changing resolution behavior. 99 | 100 | More info can be found in the article about [Lazy Dependency Injection for .NET](https://dev.to/hypercodeplace/lazy-dependency-injection-37en). 101 | 102 | [Lazy injection for Unity container](https://github.com/servicetitan/lazy-proxy-unity) 103 | 104 | [Lazy injection for Autofac container](https://github.com/servicetitan/lazy-proxy-autofac) 105 | 106 | ## License 107 | 108 | This project is licensed under the Apache License, Version 2.0. - see the [LICENSE](https://github.com/servicetitan/lazy-proxy/blob/master/LICENSE) file for details. 109 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /LazyProxy/LazyProxyBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Reflection.Emit; 7 | 8 | namespace LazyProxy 9 | { 10 | /// 11 | /// Is used to create at runtime a lazy proxy type or an instance of this type. 12 | /// 13 | public static class LazyProxyBuilder 14 | { 15 | private const string DynamicAssemblyName = "LazyProxy.DynamicTypes"; 16 | private const string LazyProxyTypeSuffix = "LazyProxyImpl"; 17 | private const string ServiceFieldName = "_service"; 18 | 19 | private static readonly AssemblyBuilder AssemblyBuilder = AssemblyBuilder 20 | .DefineDynamicAssembly(new AssemblyName(DynamicAssemblyName), AssemblyBuilderAccess.Run); 21 | 22 | private static readonly ModuleBuilder ModuleBuilder = AssemblyBuilder 23 | .DefineDynamicModule(DynamicAssemblyName); 24 | 25 | private static readonly ConcurrentDictionary> ProxyTypes = 26 | new ConcurrentDictionary>(); 27 | 28 | private static readonly MethodInfo CreateLazyMethod = typeof(LazyProxyImplementation) 29 | .GetMethod(nameof(LazyProxyImplementation.CreateInstance), BindingFlags.Public | BindingFlags.Static); 30 | 31 | private static readonly MethodInfo DisposeLazyMethod = typeof(LazyProxyImplementation) 32 | .GetMethod(nameof(LazyProxyImplementation.DisposeInstance), BindingFlags.Public | BindingFlags.Static); 33 | 34 | private static readonly Type DisposableInterface = typeof(IDisposable); 35 | 36 | private static readonly MethodInfo DisposeMethod = DisposableInterface 37 | .GetMethod(nameof(IDisposable.Dispose), BindingFlags.Public | BindingFlags.Instance); 38 | 39 | private static readonly Type[] InitializeMethodParameterTypes = {typeof(Func)}; 40 | 41 | private static readonly Type LazyProxyBaseType = typeof(LazyProxyBase); 42 | 43 | private static readonly Type LazyType = typeof(Lazy<>); 44 | 45 | /// 46 | /// Defines at runtime a class that implements interface T 47 | /// and proxies all invocations to of this interface. 48 | /// 49 | /// The interface proxy type implements. 50 | /// The lazy proxy type. 51 | public static Type GetType() where T : class 52 | { 53 | return GetType(typeof(T)); 54 | } 55 | 56 | /// 57 | /// Defines at runtime a class that implements interface of Type 58 | /// and proxies all invocations to of this interface. 59 | /// 60 | /// The interface proxy type implements. 61 | /// The lazy proxy type. 62 | public static Type GetType(Type type) 63 | { 64 | // There is no way to constraint it on the compilation step. 65 | if (!type.IsInterface) 66 | { 67 | throw new NotSupportedException("The lazy proxy is supported only for interfaces."); 68 | } 69 | 70 | var interfaceType = type.IsConstructedGenericType 71 | ? type.GetGenericTypeDefinition() 72 | : type; 73 | 74 | // Lazy is used to guarantee the valueFactory is invoked only once. 75 | // More info: http://reedcopsey.com/2011/01/16/concurrentdictionarytkeytvalue-used-with-lazyt/ 76 | var lazy = ProxyTypes.GetOrAdd(interfaceType, t => new Lazy(() => DefineProxyType(t))); 77 | var proxyType = lazy.Value; 78 | 79 | return type.IsConstructedGenericType 80 | ? proxyType.MakeGenericType(type.GetGenericArguments()) 81 | : proxyType; 82 | } 83 | 84 | /// 85 | /// Creates a lazy proxy type instance using a value factory. 86 | /// 87 | /// The function real value returns. 88 | /// The interface proxy type implements. 89 | /// The lazy proxy type instance. 90 | public static T CreateInstance(Func valueFactory) where T : class 91 | { 92 | return (T) CreateInstance(typeof(T), valueFactory); 93 | } 94 | 95 | /// 96 | /// Creates a lazy proxy type instance using a value factory. 97 | /// 98 | /// The interface proxy type implements. 99 | /// The function real value returns. 100 | /// The lazy proxy type instance. 101 | public static object CreateInstance(Type type, Func valueFactory) 102 | { 103 | var proxyType = GetType(type); 104 | 105 | // Using 'Initialize' method after the instance creation allows to improve performance 106 | // because Activator.CreateInstance method performance is much worse with arguments. 107 | var instance = (LazyProxyBase) Activator.CreateInstance(proxyType); 108 | instance.Initialize(valueFactory); 109 | 110 | return instance; 111 | } 112 | 113 | /// 114 | /// Generate the lazy proxy type at runtime. 115 | /// 116 | /// 117 | /// 118 | /// // Here is an example of the generated code: 119 | /// public interface IMyService { void Foo(); } 120 | /// 121 | /// public class LazyProxyImpl_1eb94ccd79fd48af8adfbc97c76c10ff_IMyService : IMyService 122 | /// { 123 | /// private Lazy<IMyService> _service; 124 | /// 125 | /// public void Initialize(Func<object> valueFactory) 126 | /// { 127 | /// _service = LazyProxyImplementation.CreateInstance<IMyService>(valueFactory); 128 | /// } 129 | /// 130 | /// public void Foo() => _service.Value.Foo(); 131 | /// } 132 | /// 133 | /// 134 | /// 135 | /// The interface proxy type implements. 136 | /// The lazy proxy type. 137 | private static Type DefineProxyType(Type type) 138 | { 139 | // Add a guid to avoid problems with defining generic types with different type parameters. 140 | // Dashes are allowed by IL but they are removed to match the class names in C#. 141 | var guid = Guid.NewGuid().ToString().Replace("-", ""); 142 | 143 | var typeName = $"{type.Namespace}.{LazyProxyTypeSuffix}_{guid}_{type.Name}"; 144 | 145 | return ModuleBuilder.DefineType(typeName, TypeAttributes.Public, LazyProxyBaseType) 146 | .AddGenericParameters(type) 147 | .AddInterface(type) 148 | .AddServiceField(type, out var serviceField) 149 | .AddInitializeMethod(type, serviceField) 150 | .AddMethods(type, serviceField) 151 | .AddDisposeMethodIfNeeded(type, serviceField) 152 | .CreateTypeInfo(); 153 | } 154 | 155 | private static TypeBuilder AddGenericParameters(this TypeBuilder typeBuilder, Type type) 156 | { 157 | if (type.IsGenericTypeDefinition) 158 | { 159 | AddGenericParameters(type.GetGenericArguments, typeBuilder.DefineGenericParameters); 160 | } 161 | 162 | return typeBuilder; 163 | } 164 | 165 | private static TypeBuilder AddInterface(this TypeBuilder typeBuilder, Type type) 166 | { 167 | typeBuilder.AddInterfaceImplementation(type); 168 | return typeBuilder; 169 | } 170 | 171 | private static TypeBuilder AddServiceField(this TypeBuilder typeBuilder, 172 | Type type, out FieldInfo serviceField) 173 | { 174 | serviceField = typeBuilder.DefineField( 175 | ServiceFieldName, 176 | LazyType.MakeGenericType(type), 177 | FieldAttributes.Private); 178 | 179 | return typeBuilder; 180 | } 181 | 182 | private static TypeBuilder AddInitializeMethod(this TypeBuilder typeBuilder, Type type, FieldInfo serviceField) 183 | { 184 | var methodBuilder = typeBuilder.DefineMethod( 185 | nameof(LazyProxyBase.Initialize), 186 | MethodAttributes.Family | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.Virtual, 187 | null, 188 | InitializeMethodParameterTypes 189 | ); 190 | 191 | var createLazyMethod = CreateLazyMethod.MakeGenericMethod(type); 192 | 193 | var generator = methodBuilder.GetILGenerator(); 194 | 195 | generator.Emit(OpCodes.Ldarg_0); 196 | generator.Emit(OpCodes.Ldarg_1); 197 | generator.Emit(OpCodes.Call, createLazyMethod); 198 | generator.Emit(OpCodes.Stfld, serviceField); 199 | generator.Emit(OpCodes.Ret); 200 | 201 | return typeBuilder; 202 | } 203 | 204 | private static TypeBuilder AddMethods(this TypeBuilder typeBuilder, Type type, FieldInfo serviceField) 205 | { 206 | var methods = GetMethods(type); 207 | var getServiceValueMethod = GetGetServiceValueMethod(serviceField); 208 | 209 | foreach (var method in methods) 210 | { 211 | var parameterTypes = method.GetParameters() 212 | .Select(p => p.ParameterType) 213 | .ToArray(); 214 | 215 | var methodBuilder = typeBuilder.DefineMethod( 216 | method.Name, 217 | MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot, 218 | method.ReturnType, 219 | parameterTypes 220 | ); 221 | 222 | if (method.IsGenericMethod) 223 | { 224 | AddGenericParameters(method.GetGenericArguments, methodBuilder.DefineGenericParameters); 225 | } 226 | 227 | var generator = methodBuilder.GetILGenerator(); 228 | 229 | generator.Emit(OpCodes.Ldarg_0); 230 | generator.Emit(OpCodes.Ldfld, serviceField); 231 | generator.Emit(OpCodes.Call, getServiceValueMethod); 232 | 233 | for (var i = 1; i < parameterTypes.Length + 1; i++) 234 | { 235 | generator.Emit(OpCodes.Ldarg, i); 236 | } 237 | 238 | generator.Emit(OpCodes.Tailcall); 239 | generator.Emit(OpCodes.Callvirt, method); 240 | generator.Emit(OpCodes.Ret); 241 | 242 | typeBuilder.DefineMethodOverride(methodBuilder, method); 243 | } 244 | 245 | return typeBuilder; 246 | } 247 | 248 | private static TypeBuilder AddDisposeMethodIfNeeded(this TypeBuilder typeBuilder, Type type, FieldInfo serviceField) 249 | { 250 | if (!DisposableInterface.IsAssignableFrom(type)) { 251 | return typeBuilder; 252 | } 253 | 254 | var methodBuilder = typeBuilder.DefineMethod( 255 | DisposeMethod.Name, 256 | MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot, 257 | DisposeMethod.ReturnType, 258 | Array.Empty() 259 | ); 260 | 261 | var disposeLazyMethod = DisposeLazyMethod.MakeGenericMethod(type); 262 | 263 | var generator = methodBuilder.GetILGenerator(); 264 | 265 | generator.Emit(OpCodes.Ldarg_0); 266 | generator.Emit(OpCodes.Ldfld, serviceField); 267 | generator.Emit(OpCodes.Call, disposeLazyMethod); 268 | generator.Emit(OpCodes.Ret); 269 | 270 | typeBuilder.DefineMethodOverride(methodBuilder, DisposeMethod); 271 | 272 | return typeBuilder; 273 | } 274 | 275 | private static IEnumerable GetMethods(Type type) 276 | { 277 | const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance; 278 | 279 | var isDisposable = DisposableInterface.IsAssignableFrom(type); 280 | return type.GetMethods(flags) 281 | .Concat(type.GetInterfaces() 282 | .SelectMany(@interface => @interface.GetMethods(flags))) 283 | .Where(method => !isDisposable || method.Name != nameof(IDisposable.Dispose)) 284 | .Distinct(); 285 | } 286 | 287 | private static MethodInfo GetGetServiceValueMethod(FieldInfo serviceField) 288 | { 289 | // ReSharper disable once PossibleNullReferenceException 290 | return serviceField.FieldType.GetProperty("Value").GetGetMethod(true); 291 | } 292 | 293 | private static void AddGenericParameters( 294 | Func> getGenericParameters, 295 | Func> defineGenericParameters) 296 | { 297 | var genericParameters = getGenericParameters(); 298 | 299 | var genericParametersNames = genericParameters 300 | .Select(genericType => genericType.Name) 301 | .ToArray(); 302 | 303 | var definedGenericParameters = defineGenericParameters(genericParametersNames); 304 | 305 | for (var i = 0; i < genericParameters.Count; i++) 306 | { 307 | var genericParameter = genericParameters[i]; 308 | var definedGenericParameter = definedGenericParameters[i]; 309 | var genericParameterAttributes = genericParameter.GenericParameterAttributes 310 | & ~GenericParameterAttributes.Covariant 311 | & ~GenericParameterAttributes.Contravariant; 312 | 313 | definedGenericParameter.SetGenericParameterAttributes(genericParameterAttributes); 314 | 315 | var genericParameterConstraints = genericParameter.GetGenericParameterConstraints(); 316 | if (!genericParameterConstraints.Any()) 317 | { 318 | continue; 319 | } 320 | 321 | var interfaceConstraints = new List(genericParameterConstraints.Length); 322 | 323 | foreach (var constraint in genericParameterConstraints) 324 | { 325 | if (constraint.IsInterface) 326 | { 327 | interfaceConstraints.Add(constraint); 328 | } 329 | else 330 | { 331 | definedGenericParameter.SetBaseTypeConstraint(constraint); 332 | } 333 | } 334 | 335 | if (interfaceConstraints.Any()) 336 | { 337 | definedGenericParameter.SetInterfaceConstraints(interfaceConstraints.ToArray()); 338 | } 339 | } 340 | } 341 | } 342 | } 343 | -------------------------------------------------------------------------------- /LazyProxy.Tests/LazyProxyBuilderTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using Moq; 4 | using Xunit; 5 | 6 | namespace LazyProxy.Tests 7 | { 8 | public class LazyProxyBuilderTests 9 | { 10 | public interface IBaseArgument { } 11 | 12 | public interface IOtherBaseArgument { } 13 | 14 | public abstract class BaseArgument : IBaseArgument, IOtherBaseArgument { } 15 | 16 | public abstract class BaseArgument2 { } 17 | 18 | public struct TestArgument : IBaseArgument, IOtherBaseArgument { } 19 | 20 | // ReSharper disable once MemberCanBePrivate.Global 21 | public class TestArgument2 : BaseArgument { } 22 | 23 | // ReSharper disable once MemberCanBePrivate.Global 24 | public class TestArgument3 : BaseArgument { } 25 | 26 | // ReSharper disable once MemberCanBePrivate.Global 27 | public class TestArgument4 : BaseArgument2, IBaseArgument { } 28 | 29 | private class TestException : Exception { } 30 | 31 | public interface IParentTestService 32 | { 33 | int ParentProperty { get; set; } 34 | 35 | string ParentMethod(bool arg); 36 | } 37 | 38 | // ReSharper disable once MemberCanBePrivate.Global 39 | public interface ITestService : IParentTestService 40 | { 41 | TestArgument Property { get; set; } 42 | string this[int i] { get; set; } 43 | 44 | void VoidMethod(); 45 | Task MethodAsync(string arg); 46 | string Method(string arg1, int arg2, TestArgument arg3); 47 | string MethodWithDefaultValue(string arg = "arg"); 48 | string MethodWithOutValue(out string arg); 49 | string MethodWithRefValue(ref TestArgument arg); 50 | 51 | void GenericMethod() 52 | where T : IBaseArgument, IOtherBaseArgument { } 53 | 54 | string GenericMethod(string arg) 55 | where T1 : class, IBaseArgument, new() 56 | where T2 : struct 57 | where T3 : BaseArgument2, IBaseArgument; 58 | } 59 | 60 | // ReSharper disable once MemberCanBePrivate.Global 61 | public interface IGenericTestService 62 | where T : class, IBaseArgument, IOtherBaseArgument, new() 63 | where TIn : struct 64 | where TOut : BaseArgument2, IBaseArgument 65 | { 66 | TOut Method1(T arg1, TIn arg2); 67 | T Method2(T arg1, TIn arg2); 68 | // ReSharper disable once UnusedMember.Global 69 | T GenericMethod(TIn arg); 70 | } 71 | 72 | // ReSharper disable once MemberCanBePrivate.Global 73 | public interface IGenericTestService2 74 | where TIn : class 75 | where TOut : class 76 | { 77 | } 78 | 79 | // ReSharper disable once UnusedMember.Global 80 | // ReSharper disable once MemberCanBePrivate.Global 81 | public abstract class AbstractTestService { } 82 | 83 | [Fact] 84 | public void ProxyMustImplementInterface() 85 | { 86 | var proxyType = LazyProxyBuilder.GetType(); 87 | 88 | Assert.Contains(typeof(ITestService), proxyType.GetInterfaces()); 89 | } 90 | 91 | [Fact] 92 | public void ExceptionMustBeThrownForBuildingProxyByClass() 93 | { 94 | Assert.Throws( 95 | LazyProxyBuilder.GetType); 96 | } 97 | 98 | [Fact] 99 | public void SameTypeMustBeReturnedInCaseDoubleRegistration() 100 | { 101 | var proxyType1 = LazyProxyBuilder.GetType(); 102 | var proxyType2 = LazyProxyBuilder.GetType(); 103 | 104 | Assert.Equal(proxyType1, proxyType2); 105 | } 106 | 107 | [Fact] 108 | public void ServiceCtorMustBeExecutedAfterMethodIsCalledAndOnlyOnce() 109 | { 110 | var constructorCounter = 0; 111 | var proxy = LazyProxyBuilder.CreateInstance(() => 112 | { 113 | constructorCounter++; 114 | return Mock.Of(); 115 | }); 116 | 117 | Assert.Equal(0, constructorCounter); 118 | 119 | proxy.VoidMethod(); 120 | 121 | Assert.Equal(1, constructorCounter); 122 | 123 | proxy.VoidMethod(); 124 | 125 | Assert.Equal(1, constructorCounter); 126 | } 127 | 128 | [Fact] 129 | public void MethodsMustBeProxied() 130 | { 131 | const string arg1 = "test"; 132 | const int arg2 = 7; 133 | var arg3 = new TestArgument(); 134 | const bool arg4 = true; 135 | const string result1 = "result1"; 136 | const string result2 = "result2"; 137 | 138 | var proxy = LazyProxyBuilder.CreateInstance(() => 139 | { 140 | var mock = new Mock(MockBehavior.Strict); 141 | 142 | mock.Setup(s => s.Method(arg1, arg2, arg3)).Returns(result1); 143 | mock.Setup(s => s.ParentMethod(arg4)).Returns(result2); 144 | 145 | return mock.Object; 146 | }); 147 | 148 | Assert.Equal(result1, proxy.Method(arg1, arg2, arg3)); 149 | Assert.Equal(result2, proxy.ParentMethod(arg4)); 150 | } 151 | 152 | [Fact] 153 | public async Task AsyncMethodsMustBeProxied() 154 | { 155 | const string arg = "arg"; 156 | const string result = "result"; 157 | 158 | var proxy = LazyProxyBuilder.CreateInstance(() => 159 | { 160 | var mock = new Mock(MockBehavior.Strict); 161 | 162 | mock.Setup(s => s.MethodAsync(arg)).ReturnsAsync(result); 163 | 164 | return mock.Object; 165 | }); 166 | 167 | var actualResult = await proxy.MethodAsync(arg); 168 | 169 | Assert.Equal(result, actualResult); 170 | } 171 | 172 | [Fact] 173 | public void MethodsWithDefaultValuesMustBeProxied() 174 | { 175 | const string defaultArg = "arg"; 176 | const string result = "result"; 177 | 178 | var proxy = LazyProxyBuilder.CreateInstance(() => 179 | { 180 | var mock = new Mock(MockBehavior.Strict); 181 | 182 | mock.Setup(s => s.MethodWithDefaultValue(defaultArg)).Returns(result); 183 | 184 | return mock.Object; 185 | }); 186 | 187 | var actualResult = proxy.MethodWithDefaultValue(); 188 | 189 | Assert.Equal(result, actualResult); 190 | } 191 | 192 | [Fact] 193 | public void MethodsWithOutValuesMustBeProxied() 194 | { 195 | var expectedOutArg = "arg"; 196 | const string expectedResult = "result"; 197 | 198 | var proxy = LazyProxyBuilder.CreateInstance(() => 199 | { 200 | var mock = new Mock(MockBehavior.Strict); 201 | 202 | mock.Setup(s => s.MethodWithOutValue(out expectedOutArg)).Returns(expectedResult); 203 | 204 | return mock.Object; 205 | }); 206 | 207 | var actualResult = proxy.MethodWithOutValue(out var actualOutArg); 208 | 209 | Assert.Equal(expectedResult, actualResult); 210 | Assert.Equal(expectedOutArg, actualOutArg); 211 | } 212 | 213 | [Fact] 214 | public void MethodsWithRefValuesMustBeProxied() 215 | { 216 | var refArg = new TestArgument(); 217 | const string expectedResult = "result"; 218 | 219 | var proxy = LazyProxyBuilder.CreateInstance(() => 220 | { 221 | var mock = new Mock(MockBehavior.Strict); 222 | 223 | // ReSharper disable once AccessToModifiedClosure 224 | mock.Setup(s => s.MethodWithRefValue(ref refArg)).Returns(expectedResult); 225 | 226 | return mock.Object; 227 | }); 228 | 229 | var actualResult = proxy.MethodWithRefValue(ref refArg); 230 | 231 | Assert.Equal(expectedResult, actualResult); 232 | } 233 | 234 | [Fact] 235 | public void GenericMethodsMustBeProxied() 236 | { 237 | const string arg = "arg"; 238 | const string expectedResult = "result"; 239 | 240 | var proxy = LazyProxyBuilder.CreateInstance(() => 241 | { 242 | var mock = new Mock(MockBehavior.Strict); 243 | 244 | mock 245 | .Setup(s => s.GenericMethod(arg)) 246 | .Returns(expectedResult); 247 | 248 | return mock.Object; 249 | }); 250 | 251 | var actualResult = proxy.GenericMethod(arg); 252 | 253 | Assert.Equal(expectedResult, actualResult); 254 | } 255 | 256 | [Fact] 257 | public void PropertyGettersMustBeProxied() 258 | { 259 | var result1 = new TestArgument(); 260 | const int result2 = 3; 261 | 262 | var proxy = LazyProxyBuilder.CreateInstance(() => 263 | { 264 | var mock = new Mock(MockBehavior.Strict); 265 | 266 | mock.Setup(s => s.Property).Returns(result1); 267 | mock.Setup(s => s.ParentProperty).Returns(result2); 268 | 269 | return mock.Object; 270 | }); 271 | 272 | Assert.Equal(result1, proxy.Property); 273 | Assert.Equal(result2, proxy.ParentProperty); 274 | } 275 | 276 | [Fact] 277 | public void PropertySettersMustBeProxied() 278 | { 279 | var value1 = new TestArgument(); 280 | const int value2 = 3; 281 | 282 | Mock mock = null; 283 | 284 | var proxy = LazyProxyBuilder.CreateInstance(() => 285 | { 286 | mock = new Mock(MockBehavior.Strict); 287 | 288 | mock.SetupSet(s => s.Property = value1); 289 | mock.SetupSet(s => s.ParentProperty = value2); 290 | 291 | return mock.Object; 292 | }); 293 | 294 | proxy.Property = value1; 295 | proxy.ParentProperty = value2; 296 | 297 | mock.VerifySet(s => s.Property = value1); 298 | mock.VerifySet(s => s.ParentProperty = value2); 299 | } 300 | 301 | [Fact] 302 | public void IndexerGettersMustBeProxied() 303 | { 304 | const int arg = 3; 305 | const string result = "result"; 306 | 307 | var proxy = LazyProxyBuilder.CreateInstance(() => 308 | { 309 | var mock = new Mock(MockBehavior.Strict); 310 | 311 | mock.Setup(s => s[arg]).Returns(result); 312 | 313 | return mock.Object; 314 | }); 315 | 316 | Assert.Equal(result, proxy[arg]); 317 | } 318 | 319 | [Fact] 320 | public void IndexerSettersMustBeProxied() 321 | { 322 | const int arg = 3; 323 | const string result = "result"; 324 | Mock mock = null; 325 | 326 | var proxy = LazyProxyBuilder.CreateInstance(() => 327 | { 328 | mock = new Mock(MockBehavior.Strict); 329 | 330 | mock.SetupSet(s => s[arg] = result); 331 | 332 | return mock.Object; 333 | }); 334 | 335 | proxy[arg] = result; 336 | 337 | mock.VerifySet(s => s[arg] = result); 338 | } 339 | 340 | [Fact] 341 | public void ExceptionsFromServiceMustBeThrown() 342 | { 343 | const bool arg = true; 344 | 345 | var proxy = LazyProxyBuilder.CreateInstance(() => 346 | { 347 | var mock = new Mock(MockBehavior.Strict); 348 | 349 | mock.Setup(s => s.ParentMethod(arg)).Throws(); 350 | 351 | return mock.Object; 352 | }); 353 | 354 | Assert.Throws(() => proxy.ParentMethod(arg)); 355 | } 356 | 357 | [Fact] 358 | public void GenericInterfacesMustBeProxied() 359 | { 360 | var arg1 = new TestArgument2(); 361 | var arg2 = new TestArgument(); 362 | var expectedResult1 = new TestArgument4(); 363 | var expectedResult2 = new TestArgument2(); 364 | 365 | var proxy = LazyProxyBuilder.CreateInstance(() => 366 | { 367 | var mock = new Mock>(MockBehavior.Strict); 368 | 369 | mock.Setup(s => s.Method1(arg1, arg2)).Returns(expectedResult1); 370 | mock.Setup(s => s.Method2(arg1, arg2)).Returns(expectedResult2); 371 | 372 | return mock.Object; 373 | }); 374 | 375 | var actualResult1 = proxy.Method1(arg1, arg2); 376 | var actualResult2 = proxy.Method2(arg1, arg2); 377 | 378 | Assert.Equal(expectedResult1, actualResult1); 379 | Assert.Equal(expectedResult2, actualResult2); 380 | } 381 | 382 | [Fact] 383 | public void GenericInterfacesMustBeProxiedByNonGenericMethod() 384 | { 385 | var arg1 = new TestArgument2(); 386 | var arg2 = new TestArgument(); 387 | var expectedResult1 = new TestArgument4(); 388 | var expectedResult2 = new TestArgument2(); 389 | 390 | var proxyObject = LazyProxyBuilder.CreateInstance( 391 | typeof(IGenericTestService), () => 392 | { 393 | var mock = new Mock>( 394 | MockBehavior.Strict); 395 | 396 | mock.Setup(s => s.Method1(arg1, arg2)).Returns(expectedResult1); 397 | mock.Setup(s => s.Method2(arg1, arg2)).Returns(expectedResult2); 398 | 399 | return mock.Object; 400 | }); 401 | 402 | var proxy = proxyObject as IGenericTestService; 403 | 404 | Assert.NotNull(proxy); 405 | 406 | var actualResult1 = proxy.Method1(arg1, arg2); 407 | var actualResult2 = proxy.Method2(arg1, arg2); 408 | 409 | Assert.Equal(expectedResult1, actualResult1); 410 | Assert.Equal(expectedResult2, actualResult2); 411 | } 412 | 413 | [Fact] 414 | public void GenericInterfaceWithDifferentTypeParametersMustBeCreatedWithoutExceptions() 415 | { 416 | var exception = Record.Exception(() => 417 | { 418 | LazyProxyBuilder.GetType(typeof(IGenericTestService<,,>)); 419 | LazyProxyBuilder.GetType>(); 420 | LazyProxyBuilder.GetType>(); 421 | }); 422 | 423 | Assert.Null(exception); 424 | } 425 | 426 | [Fact] 427 | public void GenericMethodWithMultipleInterfaceConstraintsMustBeProxied() 428 | { 429 | var exception = Record.Exception(() => 430 | { 431 | var proxy = LazyProxyBuilder.CreateInstance(Mock.Of); 432 | proxy.GenericMethod(); 433 | }); 434 | 435 | Assert.Null(exception); 436 | } 437 | 438 | [Fact] 439 | public void GenericInterfaceWithMultipleParameterTypesMustBeProxied() 440 | { 441 | var exception = Record.Exception(() => 442 | { 443 | LazyProxyBuilder.CreateInstance(Mock.Of>); 444 | }); 445 | 446 | Assert.Null(exception); 447 | } 448 | } 449 | } 450 | --------------------------------------------------------------------------------