Represents a service container with additional extension points for customizing service instances
Inheritance: IServiceContainer
Ejemplo n.º 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
        }
Ejemplo n.º 2
0
        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();
        }
Ejemplo n.º 3
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();
        }
Ejemplo n.º 4
0
 public LinFuAspectContainer(ServiceContainer container)
 {
     Proxy = new MasterProxy();
     _container = container;
     _container.PostProcessors.Add(new AspectPostProcessor());
     _container.AddService(Proxy);
 }
Ejemplo n.º 5
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));
 }
        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);
        }
Ejemplo n.º 7
0
 public LinFuAspectContainer(ServiceContainer container)
 {
     Proxy = new MasterProxy {Container = new LinFuServiceLocatorAdapter(container)};
     _container = container;
     _container.PostProcessors.Add(new AspectPostProcessor());
     _container.AddService(Proxy);
 }
        public override void PrepareBasic()
        {
            this.container = new LinFu.IoC.ServiceContainer();

            this.RegisterDummies();
            this.RegisterStandard();
            this.RegisterComplex();
        }
 private static void Inject(string serviceName, Action<IGenerateFactory<ISampleService>> usingFactory,
                            Func<IUsingLambda<ISampleService>, IGenerateFactory<ISampleService>> doInject,
                            ServiceContainer container)
 {
     // HACK: Condense the fluent statements into a single,
     // reusable line of code
     usingFactory(doInject(container.Inject<ISampleService>(serviceName)));
 }
Ejemplo n.º 10
0
 public void Prepare()
 {
     this.container = new LinFu.IoC.ServiceContainer();
     this.container.Inject <ISingleton>().Using <Singleton>().AsSingleton();
     this.container.Inject <ITransient>().Using <Transient>().OncePerRequest();
     this.container.Inject <ICombined>().Using <Combined>().OncePerRequest();
     this.container.Inject <ICalculator>().Using <Calculator>().OncePerRequest();
 }
Ejemplo n.º 11
0
        public static void InitializeServiceLocator()
        {
            ServiceContainer container = new ServiceContainer();
            AddComponentsTo(container);

            ControllerBuilder.Current.SetControllerFactory(new LinFuControllerFactory(container));
            ServiceLocator.SetLocatorProvider(() => new LinFuServiceLocator(container));
        }
Ejemplo n.º 12
0
        public override void PrepareBasic()
        {
            this.container = new LinFu.IoC.ServiceContainer();

            this.RegisterDummies();
            this.RegisterStandard();
            this.RegisterComplex();
        }
Ejemplo n.º 13
0
 public override void Prepare()
 {
     this.container = new LinFu.IoC.ServiceContainer();
     this.container.Inject<ISingleton>().Using<Singleton>().AsSingleton();
     this.container.Inject<ITransient>().Using<Transient>().OncePerRequest();
     this.container.Inject<ICombined>().Using<Combined>().OncePerRequest();
     this.container.Inject<ICalculator>().Using<Calculator>().OncePerRequest();
 }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            string directory = AppDomain.CurrentDomain.BaseDirectory;
            IServiceContainer container = new ServiceContainer();

            container.LoadFrom(directory, "*.dll");

            Console.WriteLine("Press ENTER to continue...");
            Console.ReadLine();
        }
Ejemplo n.º 15
0
        public override void Prepare()
        {
            this.container = new LinFu.IoC.ServiceContainer();

            this.RegisterDummies();
            this.RegisterStandard();
            this.RegisterComplex();
            this.RegisterMultiple();
            this.RegisterPropertyInjection();
        }
        public override void Prepare()
        {
            this.container = new LinFu.IoC.ServiceContainer();

            this.RegisterDummies();
            this.RegisterStandard();
            this.RegisterComplex();
            this.RegisterMultiple();
            this.RegisterPropertyInjection();
        }
        private static void Test(string serviceName, Action<IGenerateFactory<ISampleService>> usingFactory, Func<IUsingLambda<ISampleService>, IGenerateFactory<ISampleService>> doInject, Func<string, IServiceContainer, bool> verifyResult)
        {
            var container = new ServiceContainer();

            // HACK: Manually inject the required services into the container
            container.AddDefaultServices();

            Inject(serviceName, usingFactory, doInject, container);
            verifyResult(serviceName, container);
        }
Ejemplo n.º 18
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);
        }
Ejemplo n.º 19
0
        public void LinFu_Container_Fails_Without_Match()
        {
            var container = new ServiceContainer();
            container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "*.dll");

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

            Assert.Throws<NullReferenceException>(() => container.GetService<IBadCode>());
        }
Ejemplo n.º 20
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();
        }
Ejemplo n.º 21
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>());
        }
Ejemplo n.º 22
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);
        }
Ejemplo n.º 23
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>();
        }
Ejemplo n.º 24
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>();
            }
        }
Ejemplo n.º 25
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);
        }
Ejemplo n.º 26
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>));
        }
Ejemplo n.º 28
0
        public void ShouldBeAbleToRedirectInterfaceCallToTarget()
        {
            var container = new ServiceContainer();
            container.LoadFromBaseDirectory("*.dll");

            // The duck should call the implementation instance
            var mock = new Mock<SampleDuckTypeImplementation>();
            mock.Expect(i => i.DoSomething());

            object target = mock.Object;

            var sampleService = target.CreateDuck<ISampleService>();
            sampleService.DoSomething();

            mock.VerifyAll();
        }
Ejemplo n.º 29
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);
        }
Ejemplo n.º 30
0
        public void ClassMarkedWithPreprocessorAttributeMustBeInjectedIntoContainer()
        {
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            var loader = new Loader();
            loader.LoadDirectory(baseDirectory, "*.dll");
            var container = new ServiceContainer();

            loader.LoadInto(container);

            IEnumerable<IPreProcessor> matches = from p in container.PreProcessors
                                                  where p != null &&
                                                        p.GetType() == typeof(SamplePreprocessor)
                                                  select p;

            Assert.IsTrue(matches.Count() > 0, "The preprocessor failed to load.");
        }
Ejemplo n.º 31
0
        public void WillBeInformedIfServiceNotRegistered()
        {
            bool exceptionThrown = false;

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

            try {
                SafeServiceLocator<IValidator>.GetService();
            }
            catch (ActivationException e) {
                exceptionThrown = true;
                Assert.That(e.Message.Contains("IValidator could not be located"));
            }

            Assert.That(exceptionThrown);
        }
Ejemplo n.º 32
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));
        }
Ejemplo n.º 33
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);
        }
Ejemplo n.º 34
0
 public override void Dispose()
 {
     // Allow the container and everything it references to be disposed.
     this.container = null;
 }