PageRenderTime 111ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/src/UnitTests/IOC/InversionOfControlTests.cs

http://github.com/philiplaureano/LinFu
C# | 735 lines | 520 code | 151 blank | 64 comment | 23 complexity | daad95bf8953aa3338cc36af743a2d4a MD5 | raw file
  1. using System;
  2. using System.Linq;
  3. using System.Runtime.Serialization;
  4. using LinFu.IoC;
  5. using LinFu.IoC.Configuration;
  6. using LinFu.IoC.Interfaces;
  7. using LinFu.Proxy;
  8. using LinFu.Proxy.Interfaces;
  9. using Moq;
  10. using Xunit;
  11. using SampleLibrary;
  12. using SampleLibrary.IOC;
  13. using SampleLibrary.IOC.BugFixes;
  14. namespace LinFu.UnitTests.IOC
  15. {
  16. public class InversionOfControlTests
  17. {
  18. private static void VerifyInitializeCall(ServiceContainer container, Mock<IInitialize> mockService)
  19. {
  20. container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
  21. container.AddService(mockService.Object);
  22. mockService.Expect(i => i.Initialize(container)).AtMostOnce();
  23. // The container should return the same instance
  24. var firstResult = container.GetService<IInitialize>();
  25. var secondResult = container.GetService<IInitialize>();
  26. Assert.Same(firstResult, secondResult);
  27. // The Initialize() method should only be called once
  28. mockService.Verify();
  29. }
  30. [Fact]
  31. public void AroundInvokeClassesMarkedWithInterceptorAttributeMustGetActualTargetInstance()
  32. {
  33. var container = new ServiceContainer();
  34. container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
  35. var mockService = new Mock<ISampleWrappedInterface>();
  36. mockService.Expect(mock => mock.DoSomething());
  37. // Add the target instance
  38. container.AddService(mockService.Object);
  39. // The service must return a proxy
  40. var service = container.GetService<ISampleWrappedInterface>();
  41. Assert.NotSame(service, mockService.Object);
  42. // Execute the method and 'catch' the target instance once the method call is made
  43. service.DoSomething();
  44. var holder = container.GetService<ITargetHolder>("SampleAroundInvokeInterceptorClass");
  45. Assert.Same(holder.Target, mockService.Object);
  46. }
  47. [Fact]
  48. public void ContainerMustAllowInjectingCustomFactoriesForNamedOpenGenericTypeDefinitions()
  49. {
  50. var container = new ServiceContainer();
  51. var factory = new SampleOpenGenericFactory();
  52. var serviceName = "MyService";
  53. container.AddFactory(serviceName, typeof(ISampleGenericService<>), factory);
  54. // The container must report that it *can* create
  55. // the generic service type
  56. Assert.True(container.Contains(serviceName, typeof(ISampleGenericService<int>)));
  57. var result = container.GetService<ISampleGenericService<int>>(serviceName);
  58. Assert.NotNull(result);
  59. Assert.True(result.GetType() == typeof(SampleGenericImplementation<int>));
  60. }
  61. [Fact]
  62. public void ContainerMustAllowInjectingCustomFactoriesForOpenGenericTypeDefinitions()
  63. {
  64. var container = new ServiceContainer();
  65. var factory = new SampleOpenGenericFactory();
  66. container.AddFactory(typeof(ISampleGenericService<>), factory);
  67. // The container must report that it *can* create
  68. // the generic service type
  69. Assert.True(container.Contains(typeof(ISampleGenericService<int>)));
  70. var result = container.GetService<ISampleGenericService<int>>();
  71. Assert.NotNull(result);
  72. Assert.True(result.GetType() == typeof(SampleGenericImplementation<int>));
  73. }
  74. [Fact]
  75. public void ContainerMustAllowServicesToBeIntercepted()
  76. {
  77. var container = new ServiceContainer();
  78. container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
  79. var mock = new Mock<ISampleInterceptedInterface>();
  80. var mockInstance = mock.Object;
  81. container.AddService(mockInstance);
  82. // The container must automatically load the interceptor
  83. // from the sample assembly
  84. var result = container.GetService<ISampleInterceptedInterface>();
  85. Assert.NotSame(mockInstance, result);
  86. var proxy = (IProxy)result;
  87. Assert.NotNull(proxy.Interceptor);
  88. }
  89. [Fact]
  90. public void ContainerMustAllowServicesToBeInterceptedWithAnAroundInvokeInterceptor()
  91. {
  92. var container = new ServiceContainer();
  93. container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
  94. var mock = new Mock<ISampleWrappedInterface>();
  95. var mockInstance = mock.Object;
  96. container.AddService(mockInstance);
  97. // The container must automatically load the IAroundInvoke
  98. // from the sample assembly
  99. var result = container.GetService<ISampleWrappedInterface>();
  100. Assert.NotSame(mockInstance, result);
  101. var proxy = (IProxy)result;
  102. Assert.NotNull(proxy.Interceptor);
  103. }
  104. [Fact]
  105. public void ContainerMustAllowSurrogatesForNonExistentServiceInstances()
  106. {
  107. var container = new ServiceContainer();
  108. var mockService = new Mock<ISampleService>();
  109. var surrogate = mockService.Object;
  110. container.Inject<ISampleService>().Using((f, arguments) => surrogate).OncePerRequest();
  111. var result = container.GetService<ISampleService>();
  112. Assert.NotNull(result);
  113. Assert.Same(surrogate, result);
  114. }
  115. [Fact]
  116. public void ContainerMustAllowUntypedOpenGenericTypeRegistration()
  117. {
  118. var serviceType = typeof(ISampleGenericService<>);
  119. var implementingType = typeof(SampleGenericImplementation<>);
  120. var container = new ServiceContainer();
  121. container.AddService(serviceType, implementingType);
  122. var result = container.GetService<ISampleGenericService<long>>();
  123. Assert.NotNull(result);
  124. }
  125. [Fact]
  126. public void ContainerMustAllowUntypedServiceRegistration()
  127. {
  128. var container = new ServiceContainer();
  129. container.AddService(typeof(ISampleService), typeof(SampleClass));
  130. var service = container.GetService<ISampleService>();
  131. Assert.NotNull(service);
  132. }
  133. [Fact]
  134. public void ContainerMustBeAbleToAddExistingServiceInstances()
  135. {
  136. var container = new ServiceContainer();
  137. var mockService = new Mock<ISerializable>();
  138. container.AddService(mockService.Object);
  139. var result = container.GetService<ISerializable>();
  140. Assert.Same(result, mockService.Object);
  141. }
  142. [Fact]
  143. public void ContainerMustBeAbleToReturnAListOfServices()
  144. {
  145. var mockSampleService = new Mock<ISampleService>();
  146. var container = new ServiceContainer();
  147. // Add a bunch of dummy services
  148. for (var i = 0; i < 10; i++)
  149. {
  150. var serviceName = string.Format("Service{0}", i + 1);
  151. container.AddService(serviceName, mockSampleService.Object);
  152. }
  153. var services = container.GetServices<ISampleService>();
  154. Assert.True(services.Count() == 10);
  155. // The resulting set of services
  156. // must match the given service instance
  157. foreach (var service in services) Assert.Same(mockSampleService.Object, service);
  158. }
  159. [Fact]
  160. public void ContainerMustBeAbleToSuppressNamedServiceNotFoundErrors()
  161. {
  162. ExpectException<NamedServiceNotFoundException>(() =>
  163. {
  164. var container = new ServiceContainer();
  165. var instance = container.GetService("MyService", typeof(ISerializable));
  166. Assert.Null(instance);
  167. });
  168. }
  169. [Fact]
  170. public void ContainerMustBeAbleToSupressServiceNotFoundErrors()
  171. {
  172. var container = new ServiceContainer();
  173. container.SuppressErrors = true;
  174. var instance = container.GetService(typeof(ISerializable));
  175. Assert.Null(instance);
  176. }
  177. [Fact]
  178. public void ContainerMustCallIInitializeOnServicesCreatedFromCustomFactory()
  179. {
  180. var mockFactory = new Mock<IFactory>();
  181. var mockInitialize = new Mock<IInitialize>();
  182. mockFactory.Expect(f => f.CreateInstance(It.IsAny<IFactoryRequest>()))
  183. .Returns(mockInitialize.Object);
  184. // The IInitialize instance must be called once it
  185. // leaves the custom factory
  186. mockInitialize.Expect(i => i.Initialize(It.IsAny<IServiceContainer>()));
  187. var container = new ServiceContainer();
  188. container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "LinFu*.dll");
  189. container.AddFactory(typeof(IInitialize), mockFactory.Object);
  190. var result = container.GetService<IInitialize>();
  191. mockFactory.VerifyAll();
  192. mockInitialize.VerifyAll();
  193. }
  194. [Fact]
  195. public void ContainerMustCallPostProcessorDuringARequest()
  196. {
  197. var mockPostProcessor = new Mock<IPostProcessor>();
  198. var container = new ServiceContainer();
  199. container.PostProcessors.Add(mockPostProcessor.Object);
  200. mockPostProcessor.Expect(p =>
  201. p.PostProcess(It.Is<IServiceRequestResult>(result => result != null)));
  202. container.SuppressErrors = true;
  203. container.GetService<ISerializable>();
  204. mockPostProcessor.VerifyAll();
  205. }
  206. [Fact]
  207. public void ContainerMustGetMultipleServicesOfTheSameTypeInOneCall()
  208. {
  209. var container = new ServiceContainer();
  210. var mockServiceCount = 10;
  211. // Add a set of dummy services
  212. for (var i = 0; i < mockServiceCount; i++)
  213. {
  214. var mockService = new Mock<ISampleService>();
  215. container.AddService(string.Format("Service{0}", i + 1), mockService.Object);
  216. }
  217. var instances = container.GetServices<ISampleService>();
  218. foreach (var serviceInstance in instances)
  219. {
  220. Assert.True(typeof(ISampleService).IsAssignableFrom(serviceInstance?.GetType()));
  221. Assert.NotNull(serviceInstance);
  222. }
  223. }
  224. [Fact]
  225. public void ContainerMustGracefullyHandleRecursiveServiceDependencies()
  226. {
  227. var container = new ServiceContainer();
  228. container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "LinFu*.dll");
  229. container.AddService(typeof(SampleRecursiveTestComponent1), typeof(SampleRecursiveTestComponent1));
  230. container.AddService(typeof(SampleRecursiveTestComponent2), typeof(SampleRecursiveTestComponent2));
  231. try
  232. {
  233. var result = container.GetService<SampleRecursiveTestComponent1>();
  234. }
  235. catch (Exception ex)
  236. {
  237. Assert.True(ex?.GetType() != typeof(StackOverflowException));
  238. }
  239. }
  240. [Fact]
  241. public void ContainerMustHoldAnonymousFactoryInstance()
  242. {
  243. var mockFactory = new Mock<IFactory>();
  244. var container = new ServiceContainer();
  245. // Give it a random service interface type
  246. var serviceType = typeof(IDisposable);
  247. // Manually add the factory instance
  248. container.AddFactory(serviceType, mockFactory.Object);
  249. Assert.True(container.Contains(serviceType),
  250. $"The container needs to have a factory for service type '{serviceType}'");
  251. }
  252. [Fact]
  253. public void ContainerMustHoldNamedFactoryInstance()
  254. {
  255. var mockFactory = new Mock<IFactory>();
  256. var container = new ServiceContainer();
  257. // Randomly assign an interface type
  258. // NOTE: The actual interface type doesn't matter
  259. var serviceType = typeof(ISerializable);
  260. container.AddFactory("MyService", serviceType, mockFactory.Object);
  261. Assert.True(container.Contains("MyService", serviceType),
  262. "The container is supposed to contain a service named 'MyService'");
  263. var instance = new object();
  264. mockFactory.Expect(f => f.CreateInstance(
  265. It.Is<IFactoryRequest>(
  266. request => request.ServiceName == "MyService" && request.ServiceType == serviceType)))
  267. .Returns(instance);
  268. Assert.Same(instance, container.GetService("MyService", serviceType));
  269. }
  270. [Fact]
  271. public void ContainerMustInjectFactoryInstances()
  272. {
  273. var mockFactory = new Mock<IFactory<ISampleService>>();
  274. mockFactory.Expect(f => f.CreateInstance(It.IsAny<IFactoryRequest>())).Returns(new SampleClass());
  275. var container = new ServiceContainer();
  276. container.AddFactory(mockFactory.Object);
  277. var instance =
  278. (SampleClassWithFactoryDependency)container.AutoCreate(typeof(SampleClassWithFactoryDependency));
  279. Assert.NotNull(instance);
  280. var factory = instance.Factory;
  281. factory.CreateInstance(null);
  282. mockFactory.VerifyAll();
  283. }
  284. [Fact]
  285. public void ContainerMustListAvailableNamedServices()
  286. {
  287. var container = new ServiceContainer();
  288. container.AddService<ISampleService>("MyService", new SampleClass());
  289. var availableServices = container.AvailableServices;
  290. Assert.True(availableServices.Count() > 0);
  291. // There should be a matching service type
  292. // at this point
  293. var matches = from s in availableServices
  294. where
  295. s.ServiceType == typeof(ISampleService) &&
  296. s.ServiceName == "MyService"
  297. select s;
  298. Assert.True(matches.Count() > 0);
  299. }
  300. [Fact]
  301. public void ContainerMustListAvailableUnnamedServices()
  302. {
  303. var container = new ServiceContainer();
  304. container.AddService<ISampleService>(new SampleClass());
  305. var availableServices = container.AvailableServices;
  306. Assert.True(availableServices.Count() > 0);
  307. // There should be a matching service type
  308. // at this point
  309. var matches = from s in availableServices
  310. where s.ServiceType == typeof(ISampleService)
  311. select s;
  312. Assert.True(matches.Count() > 0);
  313. }
  314. [Fact]
  315. public void
  316. ContainerMustLoadAnyGenericServiceTypeInstanceFromAGenericConcreteClassMarkedWithTheImplementsAttribute()
  317. {
  318. var container = new ServiceContainer();
  319. container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
  320. var serviceName = "NonSpecificGenericService";
  321. // The container must be able to create any type that derives from ISampleService<T>
  322. // despite whether or not the specific generic service type is explicitly registered as a service
  323. Assert.True(container.Contains(serviceName, typeof(ISampleGenericService<int>)));
  324. Assert.True(container.Contains(serviceName, typeof(ISampleGenericService<double>)));
  325. Assert.True(container.Contains(serviceName, typeof(ISampleGenericService<string>)));
  326. // Both service types must be valid services
  327. Assert.NotNull(container.GetService<ISampleGenericService<int>>());
  328. Assert.NotNull(container.GetService<ISampleGenericService<double>>());
  329. Assert.NotNull(container.GetService<ISampleGenericService<string>>());
  330. }
  331. [Fact]
  332. public void ContainerMustLoadAssemblyFromMemory()
  333. {
  334. var container = new ServiceContainer();
  335. container.LoadFrom(typeof(SampleClass).Assembly);
  336. // Verify that the container loaded the sample assembly into memory
  337. Assert.True(container.Contains(typeof(ISampleService)));
  338. }
  339. [Fact]
  340. public void
  341. ContainerMustLoadSpecificGenericServiceTypesFromAGenericConcreteClassMarkedWithTheImplementsAttribute()
  342. {
  343. var container = new ServiceContainer();
  344. container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
  345. var serviceName = "SpecificGenericService";
  346. // The container must be able to create both registered service types
  347. Assert.True(container.Contains(serviceName, typeof(ISampleGenericService<int>)));
  348. Assert.True(container.Contains(serviceName, typeof(ISampleGenericService<double>)));
  349. // Both service types must be valid services
  350. Assert.NotNull(container.GetService<ISampleGenericService<int>>());
  351. Assert.NotNull(container.GetService<ISampleGenericService<double>>());
  352. }
  353. [Fact]
  354. public void ContainerMustReturnServiceInstance()
  355. {
  356. var mockFactory = new Mock<IFactory>();
  357. var container = new ServiceContainer();
  358. var serviceType = typeof(ISerializable);
  359. var instance = new object();
  360. container.AddFactory(serviceType, mockFactory.Object);
  361. // The container must call the IFactory.CreateInstance method
  362. mockFactory.Expect(
  363. f => f.CreateInstance(It.Is<IFactoryRequest>(request => request.ServiceType == serviceType
  364. && request.Container == container))).Returns(
  365. instance);
  366. var result = container.GetService(serviceType);
  367. Assert.NotNull(result);
  368. Assert.Same(instance, result);
  369. mockFactory.VerifyAll();
  370. }
  371. [Fact]
  372. public void ContainerMustSupportGenericAddFactoryMethod()
  373. {
  374. var container = new ServiceContainer();
  375. var mockFactory = new Mock<IFactory<ISerializable>>();
  376. var mockService = new Mock<ISerializable>();
  377. container.AddFactory(mockFactory.Object);
  378. mockFactory.Expect(f => f.CreateInstance(It.Is<IFactoryRequest>(request => request.Container == container)))
  379. .Returns(mockService.Object);
  380. Assert.NotNull(container.GetService<ISerializable>());
  381. }
  382. [Fact]
  383. public void ContainerMustSupportGenericGetServiceMethod()
  384. {
  385. var mockService = new Mock<ISerializable>();
  386. var mockFactory = new Mock<IFactory>();
  387. var container = new ServiceContainer();
  388. container.AddFactory(typeof(ISerializable), mockFactory.Object);
  389. container.AddFactory("MyService", typeof(ISerializable), mockFactory.Object);
  390. // Return the mock ISerializable instance
  391. mockFactory.Expect(f => f.CreateInstance(
  392. It.Is<IFactoryRequest>(request => request.Container == container &&
  393. request.ServiceType == typeof(ISerializable)))).Returns(
  394. mockService.Object);
  395. // Test the syntax
  396. var result = container.GetService<ISerializable>();
  397. Assert.Same(mockService.Object, result);
  398. result = container.GetService<ISerializable>("MyService");
  399. Assert.Same(mockService.Object, result);
  400. }
  401. [Fact]
  402. public void ContainerMustSupportNamedGenericAddFactoryMethod()
  403. {
  404. var container = new ServiceContainer();
  405. var mockFactory = new Mock<IFactory<ISerializable>>();
  406. var mockService = new Mock<ISerializable>();
  407. container.AddFactory("MyService", mockFactory.Object);
  408. mockFactory.Expect(f => f.CreateInstance(It.Is<IFactoryRequest>(request => request.Container == container)))
  409. .Returns(mockService.Object);
  410. Assert.NotNull(container.GetService<ISerializable>("MyService"));
  411. }
  412. [Fact]
  413. public void ContainerMustThrowErrorIfServiceNotFound()
  414. {
  415. ExpectException<ServiceNotFoundException>(() =>
  416. {
  417. var container = new ServiceContainer();
  418. var instance = container.GetService(typeof(ISerializable));
  419. Assert.Null(instance);
  420. });
  421. }
  422. [Fact]
  423. public void ContainerMustUseUnnamedAddFactoryMethodIfNameIsNull()
  424. {
  425. var mockFactory = new Mock<IFactory>();
  426. var mockService = new Mock<ISerializable>();
  427. var container = new ServiceContainer();
  428. var serviceType = typeof(ISerializable);
  429. // Add the service using a null name;
  430. // the container should register this factory
  431. // as if it had no name
  432. container.AddFactory(null, serviceType, mockFactory.Object);
  433. mockFactory.Expect(f => f.CreateInstance(
  434. It.Is<IFactoryRequest>(request => request.Container == container &&
  435. request.ServiceType == serviceType))).Returns(mockService.Object);
  436. // Verify the result
  437. var result = container.GetService<ISerializable>();
  438. Assert.Same(mockService.Object, result);
  439. }
  440. [Fact]
  441. public void ContainerMustUseUnnamedContainsMethodIfNameIsNull()
  442. {
  443. var mockFactory = new Mock<IFactory>();
  444. var mockService = new Mock<ISerializable>();
  445. var container = new ServiceContainer();
  446. var serviceType = typeof(ISerializable);
  447. // Use unnamed AddFactory method
  448. container.AddFactory(serviceType, mockFactory.Object);
  449. // The container should use the
  450. // IContainer.Contains(Type) method instead of the
  451. // IContainer.Contains(string, Type) method if the
  452. // service name is blank
  453. Assert.True(container.Contains(null, typeof(ISerializable)));
  454. }
  455. [Fact]
  456. public void ContainerMustUseUnnamedGetServiceMethodIfNameIsNull()
  457. {
  458. var mockFactory = new Mock<IFactory>();
  459. var mockService = new Mock<ISerializable>();
  460. var container = new ServiceContainer();
  461. var serviceType = typeof(ISerializable);
  462. mockFactory.Expect(
  463. f => f.CreateInstance(It.Is<IFactoryRequest>(request => request.ServiceType == serviceType)))
  464. .Returns(mockService.Object);
  465. container.AddFactory(serviceType, mockFactory.Object);
  466. var result = container.GetService(null, serviceType);
  467. Assert.Same(mockService.Object, result);
  468. }
  469. // [Fact]
  470. // [Ignore("TODO: Implement this")]
  471. // public void ContainerServicesShouldBeLazyIfProxyFactoryExists()
  472. // {
  473. // var container = new ServiceContainer();
  474. // container.AddService<IProxyFactory>(new ProxyFactory());
  475. // Assert.True(container.Contains(typeof(IProxyFactory)));
  476. //
  477. // // The instance should never be created
  478. // container.AddService(typeof(ISampleService), typeof(SampleLazyService));
  479. //
  480. // var result = container.GetService<ISampleService>();
  481. // Assert.False(SampleLazyService.IsInitialized);
  482. // }
  483. [Fact]
  484. public void
  485. ContainerShouldBeAbleToCreateAGenericServiceImplementationThatHasAConstructorWithPrimitiveArguments()
  486. {
  487. var container = new ServiceContainer();
  488. container.LoadFrom(typeof(SampleService<>).Assembly);
  489. ISampleService<int> s = null;
  490. // All fail with ServiceNotFoundException.
  491. s = container.GetService<ISampleService<int>>(42, "frobozz", false);
  492. Assert.NotNull(s);
  493. s = container.GetService<ISampleService<int>>(42, "frobozz");
  494. Assert.NotNull(s);
  495. s = container.GetService<ISampleService<int>>(42, false);
  496. Assert.NotNull(s);
  497. s = container.GetService<ISampleService<int>>(null, "frobozz", false);
  498. Assert.NotNull(s);
  499. }
  500. [Fact]
  501. public void ContainerShouldBeAbleToRegisterGenericTypeAndResolveConcreteServiceType()
  502. {
  503. var container = new ServiceContainer();
  504. container.AddService(typeof(ISampleGenericService<>),
  505. typeof(SampleGenericClassWithOpenGenericImplementation<>));
  506. var instance = container.GetService<ISampleGenericService<int>>();
  507. Assert.NotNull(instance);
  508. }
  509. [Fact]
  510. public void
  511. ContainerShouldBeAbleToRegisterGenericTypeAndResolveConcreteServiceTypeUsingTheNonGenericGetServiceMethod()
  512. {
  513. var container = new ServiceContainer();
  514. container.AddService(typeof(ISampleGenericService<>),
  515. typeof(SampleGenericClassWithOpenGenericImplementation<>));
  516. var instance = container.GetService(typeof(ISampleGenericService<int>));
  517. Assert.NotNull(instance);
  518. }
  519. [Fact]
  520. public void ContainerShouldCallPreProcessor()
  521. {
  522. var mockPreprocessor = new Mock<IPreProcessor>();
  523. var mockService = new Mock<ISampleService>();
  524. mockPreprocessor.Expect(p => p.Preprocess(It.IsAny<IServiceRequest>()));
  525. var container = new ServiceContainer();
  526. container.AddService("SomeService", mockService.Object);
  527. container.PreProcessors.Add(mockPreprocessor.Object);
  528. // The preprocessors should be called
  529. var result = container.GetService<ISampleService>("SomeService");
  530. Assert.NotNull(result);
  531. mockPreprocessor.VerifyAll();
  532. }
  533. [Fact]
  534. public void InitializerShouldOnlyBeCalledOncePerLifetime()
  535. {
  536. var container = new ServiceContainer();
  537. var mockService = new Mock<IInitialize>();
  538. VerifyInitializeCall(container, mockService);
  539. VerifyInitializeCall(container, new Mock<IInitialize>());
  540. }
  541. [Fact]
  542. public void InterceptorClassesMarkedWithInterceptorAttributeMustGetActualTargetInstance()
  543. {
  544. var container = new ServiceContainer();
  545. container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
  546. var mockService = new Mock<ISampleInterceptedInterface>();
  547. mockService.Expect(mock => mock.DoSomething());
  548. // Add the target instance
  549. container.AddService(mockService.Object);
  550. // The service must return a proxy
  551. var service = container.GetService<ISampleInterceptedInterface>();
  552. Assert.NotSame(service, mockService.Object);
  553. // Execute the method and 'catch' the target instance once the method call is made
  554. service.DoSomething();
  555. var holder = container.GetService<ITargetHolder>("SampleInterceptorClass");
  556. Assert.Same(holder.Target, mockService.Object);
  557. }
  558. [Fact]
  559. public void ShouldNotReturnNamedServicesForGetServiceCallsForAnonymousServices()
  560. {
  561. ExpectException<NamedServiceNotFoundException>(() =>
  562. {
  563. var container = new ServiceContainer();
  564. var myService = new MyService();
  565. container.AddService<IMyService>(myService);
  566. Assert.NotNull(container.GetService<IMyService>());
  567. Assert.Null(container.GetService<IMyService>("frobozz"));
  568. });
  569. }
  570. private void ExpectException<TException>(Action testToRun)
  571. where TException : Exception
  572. {
  573. try
  574. {
  575. testToRun();
  576. }
  577. catch (TException)
  578. {
  579. return;
  580. }
  581. Assert.False(true, $"Expected exception type '{typeof(TException).FullName}' not thrown");
  582. }
  583. }
  584. }