示例#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 static void Init()
 {
     ServiceContainer container = new ServiceContainer();
     container.AddService(typeof(IValidator), typeof(Validator));
     container.AddService(typeof(IEntityDuplicateChecker), typeof(EntityDuplicateCheckerStub));
     ServiceLocator.SetLocatorProvider(() => new LinFuServiceLocator(container));
 }
示例#3
0
        public Linfu()
        {
            container = new ServiceContainer();
            container.AddService(typeof(Game), LifecycleType.Singleton);
            container.AddService(typeof(Player), LifecycleType.OncePerRequest);
            container.AddService(typeof(Gun), LifecycleType.OncePerRequest);
            container.AddService(typeof(Bullet), LifecycleType.OncePerRequest);
            container.AddService<Func<Bullet>>(r => () => r.Container.GetService<Bullet>(), LifecycleType.OncePerRequest);

            container.DisableAutoFieldInjection();
            container.DisableAutoMethodInjection();
            container.DisableAutoPropertyInjection();
        }
示例#4
0
 public LinFuAspectContainer(ServiceContainer container)
 {
     Proxy = new MasterProxy {Container = new LinFuServiceLocatorAdapter(container)};
     _container = container;
     _container.PostProcessors.Add(new AspectPostProcessor());
     _container.AddService(Proxy);
 }
示例#5
0
 public LinFuAspectContainer(ServiceContainer container)
 {
     Proxy = new MasterProxy();
     _container = container;
     _container.PostProcessors.Add(new AspectPostProcessor());
     _container.AddService(Proxy);
 }
        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();
        }
示例#7
0
        public void ShouldConstructParametersFromContainer()
        {
            var targetConstructor = typeof(SampleClassWithMultipleConstructors).GetConstructor(new[] { typeof(ISampleService),
                typeof(ISampleService) });

            // Initialize the container
            var mockSampleService = new Mock<ISampleService>();
            IServiceContainer container = new ServiceContainer();
            container.AddService(mockSampleService.Object);
            container.AddService<IArgumentResolver>(new ArgumentResolver());

            // Generate the arguments using the target constructor
            object[] arguments = targetConstructor.ResolveArgumentsFrom(container);
            Assert.AreSame(arguments[0], mockSampleService.Object);
            Assert.AreSame(arguments[1], mockSampleService.Object);
        }
示例#8
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();
        }
示例#9
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 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);
        }
示例#11
0
        public void CanReturnServiceIfInitializedAndRegistered()
        {
            ServiceContainer container = new ServiceContainer();
            container.LoadFromBaseDirectory("Shaml.Data.dll");
            container.AddService("validator", typeof(IValidator), typeof(Validator), LinFu.IoC.Configuration.LifecycleType.OncePerRequest);

            ServiceLocator.SetLocatorProvider(() => new LinFuServiceLocator(container));

            IValidator validatorService = SafeServiceLocator<IValidator>.GetService();

            Assert.That(validatorService, Is.Not.Null);
        }
示例#12
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>();
            }
        }
示例#13
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>();
        }
示例#14
0
        public void ShouldAutoInjectClassCreatedWithAutoCreate()
        {
            // Configure the container
            var container = new ServiceContainer();
            container.LoadFromBaseDirectory("*.dll");

            var sampleService = new Mock<ISampleService>();
            container.AddService(sampleService.Object);

            var instance = (SampleClassWithInjectionProperties)container.AutoCreate(typeof(SampleClassWithInjectionProperties));

            // The container should initialize the SomeProperty method to match the mock ISampleService instance
            Assert.IsNotNull(instance.SomeProperty);
            Assert.AreSame(instance.SomeProperty, sampleService.Object);
        }
        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);
        }
示例#16
0
        public void CreatedServicesMustBeAbleToInitializeThemselves()
        {
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            var loader = new Loader();
            loader.LoadDirectory(baseDirectory, "*.dll");

            var mockInitialize = new Mock<IInitialize>();
            var container = new ServiceContainer();

            // The service container should call the Initialize method
            mockInitialize.Expect(target => target.Initialize(container));
            loader.LoadInto(container);

            container.AddService(mockInitialize.Object);

            var result = container.GetService<IInitialize>();
            Assert.IsNotNull(result);
            Assert.AreSame(mockInitialize.Object, result);

            mockInitialize.VerifyAll();
        }
示例#17
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();
        }
        public void ContainerMustAllowUntypedOpenGenericTypeRegistration()
        {
            Type serviceType = typeof (ISampleGenericService<>);
            Type implementingType = typeof (SampleGenericImplementation<>);

            var container = new ServiceContainer();
            container.AddService(serviceType, implementingType);

            var result = container.GetService<ISampleGenericService<long>>();
            Assert.IsNotNull(result);
        }
        public void ContainerMustBeAbleToAddExistingServiceInstances()
        {
            var container = new ServiceContainer();
            var mockService = new Mock<ISerializable>();
            container.AddService(mockService.Object);

            var result = container.GetService<ISerializable>();
            Assert.AreSame(result, mockService.Object);
        }
        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 ContainerMustAllowUntypedServiceRegistration()
        {
            var container = new ServiceContainer();
            container.AddService(typeof (ISampleService), typeof (SampleClass));

            var service = container.GetService<ISampleService>();
            Assert.IsNotNull(service);
        }
        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"));
        }
        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 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 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 ContainerMustListAvailableUnnamedServices()
        {
            var container = new ServiceContainer();
            container.AddService<ISampleService>(new SampleClass());

            IEnumerable<IServiceInfo> availableServices = container.AvailableServices;
            Assert.IsTrue(availableServices.Count() > 0);

            // There should be a matching service type
            // at this point
            IEnumerable<IServiceInfo> matches = from s in availableServices
                                                where s.ServiceType == typeof (ISampleService)
                                                select s;

            Assert.IsTrue(matches.Count() > 0);
        }
        public void ContainerMustGracefullyHandleRecursiveServiceDependencies()
        {
            var container = new ServiceContainer();
            container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "LinFu*.dll");

            container.AddService(typeof (SampleRecursiveTestComponent1), typeof (SampleRecursiveTestComponent1));
            container.AddService(typeof (SampleRecursiveTestComponent2), typeof (SampleRecursiveTestComponent2));

            try
            {
                var result = container.GetService<SampleRecursiveTestComponent1>();
            }
            catch (Exception ex)
            {
                Assert.IsNotInstanceOfType(typeof (StackOverflowException), ex);
            }
        }
        public void ContainerMustBeAbleToReturnAListOfServices()
        {
            var mockSampleService = new Mock<ISampleService>();
            var container = new ServiceContainer();

            // Add a bunch of dummy services
            for (int i = 0; i < 10; i++)
            {
                string serviceName = string.Format("Service{0}", i + 1);
                container.AddService(serviceName, mockSampleService.Object);
            }

            IEnumerable<ISampleService> services = container.GetServices<ISampleService>();
            Assert.IsTrue(services.Count() == 10);

            // The resulting set of services
            // must match the given service instance
            foreach (ISampleService service in services)
            {
                Assert.AreSame(mockSampleService.Object, service);
            }
        }
        public void ContainerMustGetMultipleServicesOfTheSameTypeInOneCall()
        {
            var container = new ServiceContainer();
            int mockServiceCount = 10;

            // Add a set of dummy services
            for (int i = 0; i < mockServiceCount; i++)
            {
                var mockService = new Mock<ISampleService>();
                container.AddService(string.Format("Service{0}", i + 1), mockService.Object);
            }

            IEnumerable<ISampleService> instances = container.GetServices<ISampleService>();
            foreach (ISampleService serviceInstance in instances)
            {
                Assert.IsInstanceOfType(typeof (ISampleService), serviceInstance);
                Assert.IsNotNull(serviceInstance);
            }
        }