GetService() 공개 메소드

Overridden. Causes the container to instantiate the service with the given service type. If the service type cannot be created, then an exception will be thrown if the IContainer.SuppressErrors property is set to false. Otherwise, it will simply return null.
This overload of the GetService method has been overridden so that its results can be handled by the postprocessors.
public GetService ( Type serviceType ) : object
serviceType System.Type The service type to instantiate.
리턴 object
예제 #1
26
        public void ScopeShouldNeverCallDisposableOnScopedObjectCreatedInAnotherThread()
        {
            var mock = new Mock<IDisposable>();

            var container = new ServiceContainer();
            container.AddService(mock.Object);

            using (var scope = container.GetService<IScope>())
            {
                var signal = new ManualResetEvent(false);
                WaitCallback callback = state =>
                                            {
                                                // Create the service instance
                                                var instance = container.GetService<IDisposable>();
                                                signal.Set();
                                            };

                ThreadPool.QueueUserWorkItem(callback);

                // Wait for the thread to execute
                WaitHandle.WaitAny(new WaitHandle[] {signal});
            }

            // The instance should never be disposed
        }
예제 #2
0
        public void ScopeShouldCallDisposableOnScopedObject()
        {
            var mock = new Mock<IDisposable>();
            mock.Expect(disposable => disposable.Dispose());

            var container = new ServiceContainer();
            container.AddService(mock.Object);

            using (var scope = container.GetService<IScope>())
            {
                // Create the service instance
                var instance = container.GetService<IDisposable>();
            }
        }
예제 #3
0
        public void ScopeShouldNeverCallDisposableOnNonScopedObject()
        {
            var mock = new Mock<IDisposable>();
            var container = new ServiceContainer();
            container.AddService(mock.Object);

            using (var scope = container.GetService<IScope>())
            {
            }

            // Create the service instance OUTSIDE the scope
            // Note: this should never be disposed
            var instance = container.GetService<IDisposable>();
        }
        public void ShouldLoadAssemblyIntoLoaderAtRuntime()
        {
            string path = Path.Combine(@"..\..\..\SampleFileWatcherLibrary\bin\Debug",
                                       AppDomain.CurrentDomain.BaseDirectory);
            string targetFile = "SampleFileWatcherLibrary.dll";
            string sourceFileName = Path.Combine(path, targetFile);

            var container = new ServiceContainer();
            container.AutoLoadFrom(AppDomain.CurrentDomain.BaseDirectory, "dummy.dll");

            // There should be nothing loaded at this point since the assembly hasn't
            // been copied to the target directory yet
            Assert.IsFalse(container.Contains(typeof (ISampleService)));

            // Copy the assembly to the target directory
            // and watch for changes
            string targetFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dummy.dll");
            File.Copy(sourceFileName, targetFileName, true);

            // Give the watcher thread enough time to load the assembly into memory
            Thread.Sleep(500);
            Assert.IsTrue(container.Contains(typeof (ISampleService)));

            var instance = container.GetService<ISampleService>();
            Assert.IsNotNull(instance);

            string typeName = instance.GetType().Name;
            Assert.AreEqual("SampleFileWatcherServiceClassAddedAtRuntime", typeName);
        }
예제 #5
0
        private static void TestPropertyInjection(string serviceName)
        {
            var mockTarget = new Mock<IInjectionTarget>();
            mockTarget.Expect(t => t.SetValue(123));
            var target = mockTarget.Object;

            var container = new ServiceContainer();
            container.AddService(serviceName, target);

            // Use the named fluent interface for
            // named instances
            if (!String.IsNullOrEmpty(serviceName))
            {
                container.Initialize<IInjectionTarget>(serviceName)
                    .With(service => service.SetValue(123));
            }
            else
            {
                // Otherwise, use the other one
                container.Initialize<IInjectionTarget>()
                    .With(service => service.SetValue(123));
            }
            var result = container.GetService<IInjectionTarget>(serviceName);
            Assert.IsNotNull(result);

            // The container should initialize the
            // service on every request
            mockTarget.VerifyAll();
        }
예제 #6
0
파일: Program.cs 프로젝트: slieser/LinFu
        static void Main(string[] args)
        {
            string directory = AppDomain.CurrentDomain.BaseDirectory;
            IServiceContainer container = new ServiceContainer();

            // Load CarLibrary3.dll; If you need load
            // all the libaries in a directory, use "*.dll" instead
            container.LoadFrom(directory, "CarLibrary3.dll");

            // Configure the container inject instances
            // into the Car class constructor
            container.Inject<IVehicle>()
                .Using(ioc => new Car(ioc.GetService<IEngine>(),
                                      ioc.GetService<IPerson>()))
                                      .OncePerRequest();

            Person person = new Person();
            person.Name = "Someone";
            person.Age = 18;

            container.AddService<IPerson>(person);
            IVehicle vehicle = container.GetService<IVehicle>();

            vehicle.Move();

            Console.WriteLine("Press ENTER to continue...");
            Console.ReadLine();
        }
예제 #7
0
        public void ShouldCallStronglyTypedFunctorInsteadOfActualFactory()
        {
            var container = new ServiceContainer();

            Func<int, int, int> addOperation1 = (a, b) => a + b;
            container.AddService("Add", addOperation1);

            Func<int, int, int, int> addOperation2 = (a, b, c) => a + b + c;
            container.AddService("Add", addOperation2);

            Func<int, int, int, int, int> addOperation3 = (a, b, c, d) => a + b + c + d;
            container.AddService("Add", addOperation3);

            Assert.AreEqual(2, container.GetService<int>("Add", 1, 1));
            Assert.AreEqual(3, container.GetService<int>("Add", 1, 1, 1));
            Assert.AreEqual(4, container.GetService<int>("Add", 1, 1, 1, 1));
        }
        public void AroundInvokeClassesMarkedWithInterceptorAttributeMustGetActualTargetInstance()
        {
            var container = new ServiceContainer();
            container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
            var mockService = new Mock<ISampleWrappedInterface>();
            mockService.Expect(mock => mock.DoSomething());

            // Add the target instance
            container.AddService(mockService.Object);

            // The service must return a proxy
            var service = container.GetService<ISampleWrappedInterface>();
            Assert.AreNotSame(service, mockService.Object);

            // Execute the method and 'catch' the target instance once the method call is made
            service.DoSomething();

            var holder = container.GetService<ITargetHolder>("SampleAroundInvokeInterceptorClass");
            Assert.AreSame(holder.Target, mockService.Object);
        }
예제 #9
0
        public void LinFu_Container_Allow_Wildcard_Matching()
        {
            var container = new ServiceContainer();
            container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "*.dll");

            SnapConfiguration.For(new LinFuAspectContainer(container)).Configure(c =>
            {
                c.IncludeNamespace("SnapTests.*");
                c.Bind<HandleErrorInterceptor>().To<HandleErrorAttribute>();
            });

            Assert.DoesNotThrow(() => container.GetService<IBadCode>());
        }
예제 #10
0
        public void ShouldFindGenericMethod()
        {
            var container = new ServiceContainer();
            container.LoadFromBaseDirectory("*.dll");

            var context = new MethodFinderContext(new Type[]{typeof(object)}, new object[0], typeof(void));
            var methods = typeof(SampleClassWithGenericMethod).GetMethods(BindingFlags.Public | BindingFlags.Instance);
            var finder = container.GetService<IMethodFinder<MethodInfo>>();
            var result = finder.GetBestMatch(methods, context);

            Assert.IsTrue(result.IsGenericMethod);
            Assert.IsTrue(result.GetGenericArguments().Count() == 1);
        }
예제 #11
0
        static void Main(string[] args)
        {
            string directory = AppDomain.CurrentDomain.BaseDirectory;
            var container = new ServiceContainer();

            // Load CarLibrary.dll; If you need load
            // all the libaries in a directory, use "*.dll" instead
            container.LoadFrom(directory, "CarLibrary.dll");

            IVehicle vehicle = container.GetService<IVehicle>();

            Console.WriteLine("Press ENTER to continue...");
            Console.ReadLine();
            return;
        }
        public void ContainerMustAllowInjectingCustomFactoriesForOpenGenericTypeDefinitions()
        {
            var container = new ServiceContainer();
            var factory = new SampleOpenGenericFactory();

            container.AddFactory(typeof (ISampleGenericService<>), factory);

            // The container must report that it *can* create
            // the generic service type
            Assert.IsTrue(container.Contains(typeof (ISampleGenericService<int>)));

            var result = container.GetService<ISampleGenericService<int>>();

            Assert.IsNotNull(result);
            Assert.IsTrue(result.GetType() == typeof (SampleGenericImplementation<int>));
        }
예제 #13
0
        public void ShouldAutoInjectMethod()
        {
            var container = new ServiceContainer();
            container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "LinFu*.dll");

            var instance = new SampleClassWithInjectionMethod();

            // Initialize the container
            container.Inject<ISampleService>().Using<SampleClass>().OncePerRequest();
            container.Inject<ISampleService>("MyService").Using(c => instance).OncePerRequest();

            var result = container.GetService<ISampleService>("MyService");
            Assert.AreSame(result, instance);

            // On initialization, the instance.Property value
            // should be a SampleClass type
            Assert.IsNotNull(instance.Property);
            Assert.IsInstanceOfType(typeof(SampleClass), instance.Property);
        }
예제 #14
0
        public void LazyObjectShouldNeverBeInitialized()
        {
            var container = new ServiceContainer();
            container.AddService<IProxyFactory>(new ProxyFactory());
            container.AddService<IMethodBuilder<MethodInfo>>(new MethodBuilder());

            Assert.IsTrue(container.Contains(typeof (IProxyFactory)));

            var proxyFactory = container.GetService<IProxyFactory>();
            var interceptor = new LazyInterceptor<ISampleService>(() => new SampleLazyService());

            SampleLazyService.Reset();
            // The instance should be uninitialized at this point
            var proxy = proxyFactory.CreateProxy<ISampleService>(interceptor);
            Assert.IsFalse(SampleLazyService.IsInitialized);

            // The instance should be initialized once the method is called
            proxy.DoSomething();
            Assert.IsTrue(SampleLazyService.IsInitialized);
        }
예제 #15
0
파일: Program.cs 프로젝트: jam231/LinFu
        static void Main(string[] args)
        {
            string directory = AppDomain.CurrentDomain.BaseDirectory;
            IServiceContainer container = new ServiceContainer();

            // Load CarLibrary2.dll; If you need load
            // all the libaries in a directory, use "*.dll" instead
            container.LoadFrom(directory, "CarLibrary2.dll");

            Person person = new Person();
            person.Name = "Someone";
            person.Age = 18;

            container.AddService<IPerson>(person);
            IVehicle vehicle = container.GetService<IVehicle>();

            vehicle.Move();

            Console.WriteLine("Press ENTER to continue...");
            Console.ReadLine();
        }
예제 #16
0
        public void ShouldAutoInjectPropertyWithoutCustomAttribute()
        {
            var container = new ServiceContainer();
            container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "LinFu*.dll");

            var instance = new SampleClassWithUnmarkedInjectionProperties();

            // Initialize the container with the dummy service
            container.Inject<ISampleService>().Using<SampleClass>().OncePerRequest();
            container.Inject<ISampleService>("MyService").Using(c => instance).OncePerRequest();

            // Enable automatic property injection for every property
            container.SetCustomPropertyInjectionAttribute(null);

            // Get the service instance
            var result = container.GetService<ISampleService>("MyService");
            Assert.AreSame(result, instance);

            // Ensure that the injection occurred
            Assert.IsNotNull(instance.SomeProperty);
            Assert.IsInstanceOfType(typeof(SampleClass), instance.SomeProperty);
        }
예제 #17
0
        static void Main()
        {
            #region LinFu

            //создаем LinFu IoC контейнер
            var container = new ServiceContainer();
            //настраиваем контейнер
            container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "Logger.dll");

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //Для хранилища SQL Server
            Application.Run(new Form1(container.GetService<ISqlRepository>()));

            //Для хранилища XML файл
            //Application.Run(new Form1(container.GetService<IXmlRepository>()));

            #endregion

            #region Unity

            ////создаем IoC Unity
            //IUnityContainer container = new UnityContainer();

            ////Для хранилища SQL Server
            //container.RegisterType(typeof(IRepository), typeof(EFRepository));

            ////Для хранилища XML файл
            //container.RegisterType(typeof(IRepository), typeof(XmlRepository));

            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(container.Resolve<Form1>());

            #endregion
        }
 public void ContainerMustThrowErrorIfServiceNotFound()
 {
     var container = new ServiceContainer();
     object instance = container.GetService(typeof (ISerializable));
     Assert.IsNull(instance, "The container is supposed to return a null instance");
 }
        public void ContainerMustReturnServiceInstance()
        {
            var mockFactory = new Mock<IFactory>();
            var container = new ServiceContainer();

            Type serviceType = typeof (ISerializable);
            var instance = new object();

            container.AddFactory(serviceType, mockFactory.Object);

            // The container must call the IFactory.CreateInstance method
            mockFactory.Expect(
                f => f.CreateInstance(It.Is<IFactoryRequest>(request => request.ServiceType == serviceType
                                                                        && request.Container == container))).Returns(
                                                                            instance);

            object result = container.GetService(serviceType);
            Assert.IsNotNull(result, "The container failed to return the given service instance");
            Assert.AreSame(instance, result, "The service instance returned does not match the given instance");

            mockFactory.VerifyAll();
        }
        private static void VerifyInitializeCall(ServiceContainer container, Mock<IInitialize> mockService)
        {
            container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
            container.AddService(mockService.Object);

            mockService.Expect(i => i.Initialize(container)).AtMostOnce();

            // The container should return the same instance
            var firstResult = container.GetService<IInitialize>();
            var secondResult = container.GetService<IInitialize>();
            Assert.AreSame(firstResult, secondResult);

            // The Initialize() method should only be called once
            mockService.Verify();
        }
        public void ContainerMustAllowServicesToBeIntercepted()
        {
            var container = new ServiceContainer();
            container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "*.dll");

            var mock = new Mock<ISampleInterceptedInterface>();
            ISampleInterceptedInterface mockInstance = mock.Object;
            container.AddService(mockInstance);

            // The container must automatically load the interceptor
            // from the sample assembly
            var result = container.GetService<ISampleInterceptedInterface>();
            Assert.AreNotSame(mockInstance, result);

            var proxy = (IProxy) result;
            Assert.IsNotNull(proxy.Interceptor);
        }
        public void ContainerMustSupportGenericGetServiceMethod()
        {
            var mockService = new Mock<ISerializable>();
            var mockFactory = new Mock<IFactory>();
            var container = new ServiceContainer();

            container.AddFactory(typeof (ISerializable), mockFactory.Object);
            container.AddFactory("MyService", typeof (ISerializable), mockFactory.Object);

            // Return the mock ISerializable instance
            mockFactory.Expect(f => f.CreateInstance(
                It.Is<IFactoryRequest>(request => request.Container == container &&
                                                  request.ServiceType == typeof (ISerializable)))).Returns(
                                                      mockService.Object);

            // Test the syntax
            var result = container.GetService<ISerializable>();
            Assert.AreSame(mockService.Object, result);

            result = container.GetService<ISerializable>("MyService");
            Assert.AreSame(mockService.Object, result);
        }
        public void ShouldNotReturnNamedServicesForGetServiceCallsForAnonymousServices()
        {
            var container = new ServiceContainer();
            var myService = new MyService();
            container.AddService<IMyService>(myService);

            Assert.IsNotNull(container.GetService<IMyService>());

            Assert.IsNull(container.GetService<IMyService>("frobozz"));
        }
        public void ContainerShouldBeAbleToRegisterGenericTypeAndResolveConcreteServiceTypeUsingTheNonGenericGetServiceMethod()
        {
            var container = new ServiceContainer();
            container.AddService(typeof (ISampleGenericService<>),
                                 typeof (SampleGenericClassWithOpenGenericImplementation<>));

            object instance = container.GetService(typeof (ISampleGenericService<int>));
            Assert.IsNotNull(instance);
        }
        public void ContainerShouldCallPreProcessor()
        {
            var mockPreprocessor = new Mock<IPreProcessor>();
            var mockService = new Mock<ISampleService>();

            mockPreprocessor.Expect(p => p.Preprocess(It.IsAny<IServiceRequest>()));

            var container = new ServiceContainer();
            container.AddService("SomeService", mockService.Object);
            container.PreProcessors.Add(mockPreprocessor.Object);

            // The preprocessors should be called
            var result = container.GetService<ISampleService>("SomeService");
            Assert.IsNotNull(result);

            mockPreprocessor.VerifyAll();
        }
        public void ContainerShouldBeAbleToCreateAGenericServiceImplementationThatHasAConstructorWithPrimitiveArguments()
        {
            var container = new ServiceContainer();
            container.LoadFrom(typeof (SampleService<>).Assembly);

            ISampleService<int> s = null;
            // All fail with ServiceNotFoundException.
            s = container.GetService<ISampleService<int>>(42, "frobozz", false);
            Assert.IsNotNull(s);

            s = container.GetService<ISampleService<int>>(42, "frobozz");
            Assert.IsNotNull(s);
            s = container.GetService<ISampleService<int>>(42, false);
            Assert.IsNotNull(s);

            s = container.GetService<ISampleService<int>>(null, "frobozz", false);
            Assert.IsNotNull(s);
        }
        public void ContainerServicesShouldBeLazyIfProxyFactoryExists()
        {
            var container = new ServiceContainer();
            container.AddService<IProxyFactory>(new ProxyFactory());
            Assert.IsTrue(container.Contains(typeof (IProxyFactory)));

            // The instance should never be created
            container.AddService(typeof (ISampleService), typeof (SampleLazyService));

            var result = container.GetService<ISampleService>();
            Assert.IsFalse(SampleLazyService.IsInitialized);
        }
        public void ContainerMustUseUnnamedGetServiceMethodIfNameIsNull()
        {
            var mockFactory = new Mock<IFactory>();
            var mockService = new Mock<ISerializable>();
            var container = new ServiceContainer();

            Type serviceType = typeof (ISerializable);
            mockFactory.Expect(
                f => f.CreateInstance(It.Is<IFactoryRequest>(request => request.ServiceType == serviceType)))
                .Returns(mockService.Object);
            container.AddFactory(serviceType, mockFactory.Object);

            object result = container.GetService(null, serviceType);

            Assert.AreSame(mockService.Object, result);
        }
        public void ContainerMustUseUnnamedAddFactoryMethodIfNameIsNull()
        {
            var mockFactory = new Mock<IFactory>();
            var mockService = new Mock<ISerializable>();

            var container = new ServiceContainer();

            Type serviceType = typeof (ISerializable);

            // Add the service using a null name;
            // the container should register this factory
            // as if it had no name
            container.AddFactory(null, serviceType, mockFactory.Object);
            mockFactory.Expect(f => f.CreateInstance(
                It.Is<IFactoryRequest>(request => request.Container == container &&
                                                  request.ServiceType == serviceType))).Returns(mockService.Object);

            // Verify the result
            var result = container.GetService<ISerializable>();
            Assert.AreSame(mockService.Object, result);
        }
        public void ContainerMustSupportNamedGenericAddFactoryMethod()
        {
            var container = new ServiceContainer();
            var mockFactory = new Mock<IFactory<ISerializable>>();
            var mockService = new Mock<ISerializable>();

            container.AddFactory("MyService", mockFactory.Object);
            mockFactory.Expect(f => f.CreateInstance(It.Is<IFactoryRequest>(request => request.Container == container)))
                .Returns(mockService.Object);

            Assert.IsNotNull(container.GetService<ISerializable>("MyService"));
        }