Ejemplo n.º 1
0
        public void BeginScope_GetInstance_AlwaysReturnsSameInstanceForTheSameScope()
        {
            //ARRANGE
            var container = new Container(builder =>
            {
                builder.Register <IDisposable, Disposable>(c => c
                                                           .With(Lifetime.PerScope)
                                                           .WithFinalizer(x => x.Dispose()));
            });

            //ACT
            Scoped scope1      = container.BeginScope();
            var    disposable1 = scope1.GetInstance <IDisposable>();
            var    disposable2 = scope1.GetInstance <IDisposable>();

            Scoped scope2      = container.BeginScope();
            var    disposable3 = scope2.GetInstance <IDisposable>();
            var    disposable4 = scope2.GetInstance <IDisposable>();


            //ASSERT
            Assert.Same(disposable1, disposable2);
            Assert.Same(disposable3, disposable4);
            Assert.NotSame(disposable1, disposable3);
        }
        public void MethodInjectAll_Scoped_InjectsCorrectDependencies()
        {
            //ARRANGE
            var container = new Container(builder =>
            {
                builder.Register <ITestService10, TestService10>();
                builder.LateInject <MethodInjectionClass>(c => c
                                                          .UseMethod(nameof(MethodInjectionClass.Inject)));
            });

            var instances = new List <MethodInjectionClass>();

            for (var i = 0; i < 10; i++)
            {
                instances.Add(new MethodInjectionClass());
            }

            //ACT
            Scoped scope = container.BeginScope();

            scope.LateInjectAll(instances);

            //ASSERT
            foreach (MethodInjectionClass instance in instances)
            {
                Assert.IsType <TestService10>(instance.TestService10);
            }
        }
Ejemplo n.º 3
0
        public void Build()
        {
            foreach (INamedTypeSymbol symbol in GetSymbolsForNativeApi())
            {
                if (symbol.TypeKind == TypeKind.Enum)
                {
                    Enums.Add(symbol.Name, symbol);
                    continue;
                }
                if (IsRefCountedTypeSymbol(symbol))
                {
                    RefCounted.Add(symbol.Name, symbol);
                    continue;
                }
                if (IsScopedTypeSymbol(symbol))
                {
                    Scoped.Add(symbol.Name, symbol);
                    continue;
                }

                if (symbol.TypeKind != TypeKind.Struct)
                {
                    continue;
                }

                if (IsSizedStruct(symbol))
                {
                    Sized.Add(symbol.Name, symbol);
                    continue;
                }

                Simple.Add(symbol.Name, symbol);
            }
        }
Ejemplo n.º 4
0
        public void Register_Resolve_Scoped()
        {
            //ARRANGE
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddScoped <IDisposable, TrackableDisposable>();
            var tracker = new Tracker();

            var container = new Container(builder =>
            {
                builder.Register <ITracker>(c => c.Inject(() => tracker));
                builder.RegisterServices(serviceCollection);

                builder.ConfigureSettings(SingularitySettings.Microsoft);
            });

            //ACT
            int         disposeCountBefore;
            IDisposable instance1, instance2;

            using (Scoped scope = container.BeginScope())
            {
                instance1          = scope.GetInstance <IDisposable>();
                instance2          = scope.GetInstance <IDisposable>();
                disposeCountBefore = tracker.DisposeCount;
            }
            int disposeCountAfter = tracker.DisposeCount;

            //ASSERT
            Assert.Same(instance1, instance2);
            Assert.IsType <TrackableDisposable>(instance1);
            Assert.Equal(0, disposeCountBefore);
            Assert.Equal(1, disposeCountAfter);
        }
Ejemplo n.º 5
0
        public CefTypeKind GetTypeKind(ITypeSymbol symbol)
        {
            if (!symbol.Name.StartsWith("cef_"))
            {
                return(CefTypeKind.Unknown);
            }

            INamedTypeSymbol value;

            if (RefCounted.TryGetValue(symbol.Name, out value) && Equals(value, symbol))
            {
                return(CefTypeKind.RefCounted);
            }
            if (Scoped.TryGetValue(symbol.Name, out value) && Equals(value, symbol))
            {
                return(CefTypeKind.Scoped);
            }
            if (Enums.TryGetValue(symbol.Name, out value) && Equals(value, symbol))
            {
                return(CefTypeKind.Enum);
            }
            if (Sized.TryGetValue(symbol.Name, out value) && Equals(value, symbol))
            {
                return(CefTypeKind.Sized);
            }
            if (Simple.TryGetValue(symbol.Name, out value) && Equals(value, symbol))
            {
                return(CefTypeKind.Simple);
            }
            throw new NotImplementedException();
        }
Ejemplo n.º 6
0
 public QueueWorker(
     IReceiverClient messageReceiver,
     Scoped <IWorkflowLaunchpad> workflowLaunchpad,
     IOptions <AzureServiceBusOptions> options,
     Func <IReceiverClient, Task> disposeReceiverAction,
     ILogger <QueueWorker> logger) : base(messageReceiver, workflowLaunchpad, options, disposeReceiverAction, logger)
 {
 }
Ejemplo n.º 7
0
 public TopicWorker(
     IReceiverClient receiverClient,
     Scoped <IWorkflowLaunchpad> workflowLaunchpad,
     IOptions <AzureServiceBusOptions> options,
     Func <IReceiverClient, Task> disposeReceiverAction,
     ILogger <TopicWorker> logger) : base(receiverClient, workflowLaunchpad, options, disposeReceiverAction, logger)
 {
 }
Ejemplo n.º 8
0
 public ValuesController(ICalculatorService calculatorService, Scoped scoped, Transient transient, Singelton singelton, LifeStyleService lifeStyleService)
 {
     _calculatorService = calculatorService;
     _scoped            = scoped;
     _transient         = transient;
     _singelton         = singelton;
     _lifeStyleService  = lifeStyleService;
 }
Ejemplo n.º 9
0
        public void WhenScopeIsDisposedCreateScopeThrows()
        {
            var disposable = new Disposable();
            var scope      = new Scoped <Disposable>(disposable);

            scope.Dispose();

            scope.Invoking(s => s.CreateLifetime()).Should().Throw <ObjectDisposedException>();
        }
Ejemplo n.º 10
0
        public DIHelper TryAddScoped <TService>() where TService : class
        {
            var serviceName = $"{typeof(TService)}";

            if (!Scoped.Contains(serviceName))
            {
                Scoped.Add(serviceName);
                ServiceCollection.TryAddScoped <TService>();
            }
            return(this);
        }
Ejemplo n.º 11
0
        private static List <TElement> CreateList <TElement>(Scoped scope, Func <Scoped, TElement>[] instanceFactories)
        {
            var list = new List <TElement>(instanceFactories.Length);

            foreach (Func <Scoped, TElement> instanceFactory in instanceFactories)
            {
                list.Add(instanceFactory.Invoke(scope));
            }

            return(list);
        }
Ejemplo n.º 12
0
        public Worker(
            IMqttClientWrapper receiverClient,
            Scoped <IWorkflowLaunchpad> workflowLaunchpad,
            Func <IMqttClientWrapper, Task> disposeReceiverAction)
        {
            _receiverClient        = receiverClient;
            _workflowLaunchpad     = workflowLaunchpad;
            _disposeReceiverAction = disposeReceiverAction;

            _receiverClient.SetMessageHandler(OnMessageReceived);
        }
Ejemplo n.º 13
0
        private static HashSet <TElement> CreateSet <TElement>(Scoped scope, Func <Scoped, TElement>[] instanceFactories)
        {
            var list = new HashSet <TElement>();

            foreach (Func <Scoped, TElement> instanceFactory in instanceFactories)
            {
                list.Add(instanceFactory.Invoke(scope));
            }

            return(list);
        }
Ejemplo n.º 14
0
        private static TElement[] CreateArray <TElement>(Scoped scope, Func <Scoped, TElement>[] instanceFactories)
        {
            var list = new TElement[instanceFactories.Length];

            for (int i = 0; i < instanceFactories.Length; i++)
            {
                list[i] = instanceFactories[i].Invoke(scope);
            }

            return(list);
        }
Ejemplo n.º 15
0
        public bool TryAddScoped <TService>() where TService : class
        {
            var serviceName = $"{typeof(TService)}";

            if (!Scoped.Contains(serviceName))
            {
                Scoped.Add(serviceName);
                ServiceCollection.TryAddScoped <TService>();
                return(true);
            }
            return(false);
        }
Ejemplo n.º 16
0
        public DIHelper TryAddScoped <TService, TImplementation>(TService tservice, TImplementation tImplementation) where TService : Type where TImplementation : Type
        {
            var serviceName = $"{tservice}{tImplementation}";

            if (!Scoped.Contains(serviceName))
            {
                Scoped.Add(serviceName);
                ServiceCollection.TryAddScoped(tservice, tImplementation);
            }

            return(this);
        }
Ejemplo n.º 17
0
        public void EntryAction_Is_Called()
        {
            // Arrange
            var wasCalled = false;

            // Act
            using (var scope = new Scoped(entryAction: () => wasCalled = true))
            {
                // Assert
                wasCalled.Should().BeTrue();
            }
        }
Ejemplo n.º 18
0
        public DIHelper TryAddScoped <TService, TImplementation>() where TService : class where TImplementation : class, TService
        {
            var serviceName = $"{typeof(TService)}{typeof(TImplementation)}";

            if (!Scoped.Contains(serviceName))
            {
                Scoped.Add(serviceName);
                ServiceCollection.TryAddScoped <TService, TImplementation>();
            }

            return(this);
        }
Ejemplo n.º 19
0
        public Worker(
            Scoped <IWorkflowLaunchpad> workflowLaunchpad,
            IClient client,
            Func <IClient, Task> disposeReceiverAction,
            ILogger <Worker> logger)
        {
            _client = client;
            _disposeReceiverAction = disposeReceiverAction;
            _logger            = logger;
            _workflowLaunchpad = workflowLaunchpad;

            _client.SubscribeWithHandler(OnMessageReceived);
        }
Ejemplo n.º 20
0
        public void HandleScopeThreadCollision_AddsInstance_Once()
        {
            //ARRANGE
            var scope    = new Scoped(new Container());
            var instance = new object();

            //ACT
            scope.HandleScopeThreadCollision(instance, typeof(object));
            var result = scope.GetOrAddScopedInstance <object>(scoped => throw new NotImplementedException(), typeof(object));

            //ASSERT
            Assert.Same(instance, result);
        }
Ejemplo n.º 21
0
        public void WhenScopeIsCreatedThenScopeDisposedLifetimeDisposesValue()
        {
            var disposable = new Disposable();
            var scope      = new Scoped <Disposable>(disposable);
            var lifetime   = scope.CreateLifetime();

            scope.Dispose();
            scope.Dispose(); // validate double dispose is still single ref count
            disposable.IsDisposed.Should().BeFalse();

            lifetime.Dispose();
            disposable.IsDisposed.Should().BeTrue();
        }
Ejemplo n.º 22
0
        /// <summary>
        ///     Creates a new tag that is scoped within the current thread. This results in all non tagged logs within this scope
        ///     being automatically tagged. This is a way of controlling ALL logging that might occur within scope without needing
        ///     to add tags to each statement.
        /// </summary>
        /// <returns></returns>
        public Scoped Scope()
        {
            LogTag currentScope = Scoped.CurrentValue;
            LogTag newScope     = new LogTag(string.Empty, this);
            Scoped retVal       = new Scoped(newScope);

            if (currentScope != null)
            {
                newScope.ScopeParent = currentScope;
            }

            return(retVal);
        }
Ejemplo n.º 23
0
        public ResolverPipeline(RegistrationStore registrationStore, IDependencyResolver[] resolvers, Scoped containerScope, SingularitySettings settings, IResolverPipeline?parentPipeline)
        {
            _settings         = settings ?? throw new ArgumentNullException(nameof(settings));
            _resolvers        = resolvers ?? throw new ArgumentNullException(nameof(resolvers));
            _parentPipeline   = parentPipeline;
            SyncRoot          = parentPipeline?.SyncRoot ?? new object();
            _containerScope   = containerScope ?? throw new ArgumentNullException(nameof(containerScope));
            RegistrationStore = registrationStore ?? throw new ArgumentNullException(nameof(registrationStore));

            if (parentPipeline != null)
            {
                CheckChildRegistrations(parentPipeline, registrationStore.Registrations, SyncRoot);
            }
        }
Ejemplo n.º 24
0
 private static void AddJobs()
 {
     SpareTime.Do("*/1 * * * *", (timer, count) =>
     {
         Scoped.Create((_, scope) =>
         {
             var services    = scope.ServiceProvider;
             var taskService = services.GetService <ITimedReminderJob>();
             $"Job Begin[{count}]-----------------------".LogInformation <Startup>();
             taskService.Do().Wait();
             $"Job End[{count}]-------------------------".LogInformation <Startup>();
         });
     }, "SyncSequence", "定时同步MES工序");
 }
Ejemplo n.º 25
0
        public InstanceFactoryResolver(RegistrationStore registrationStore, Scoped containerScope, SingularitySettings settings, InstanceFactoryResolver?parentPipeline)
        {
            Settings          = settings ?? throw new ArgumentNullException(nameof(settings));
            _resolvers        = Settings.ServiceBindingGenerators.ToArray();
            _parentPipeline   = parentPipeline;
            SyncRoot          = parentPipeline?.SyncRoot ?? new object();
            _containerScope   = containerScope ?? throw new ArgumentNullException(nameof(containerScope));
            RegistrationStore = registrationStore ?? throw new ArgumentNullException(nameof(registrationStore));

            if (parentPipeline != null)
            {
                CheckChildRegistrations(parentPipeline.RegistrationStore.Registrations, registrationStore.Registrations, SyncRoot);
            }
        }
Ejemplo n.º 26
0
        public void ExitAction_Is_Called_On_Dispose()
        {
            // Arrange
            var wasCalled = false;

            // Act
            using (var scope = new Scoped(exitAction: () => wasCalled = true))
            {
                wasCalled.Should().BeFalse("exitAction should not be called until Dispose() is called.");
                scope.Dispose();

                // Assert
                wasCalled.Should().BeTrue();
            }
        }
Ejemplo n.º 27
0
        public ValuesController(
            TransientDisposable transientDisposable,
            DependantOnTransient dependantOnTransient,
            Scoped scoped,
            DependantOnScoped dependantOnScoped,
            IServiceProvider serviceProvider,
            Singleton singleton)
        {
            _transientDisposable  = transientDisposable;
            _dependantOnTransient = dependantOnTransient;

            _scoped            = scoped;
            _dependantOnScoped = dependantOnScoped;
            _serviceProvider   = serviceProvider;
            _singleton         = singleton;
        }
Ejemplo n.º 28
0
        public void HandleScopeThreadCollision_AddsInstance_Twice_DifferentKey()
        {
            //ARRANGE
            var scope     = new Scoped(new Container());
            var instance1 = new object();
            var instance2 = new object();

            //ACT
            scope.HandleScopeThreadCollision(instance1, typeof(object));
            scope.HandleScopeThreadCollision(instance2, typeof(int));
            var result1 = scope.GetOrAddScopedInstance <object>(scoped => throw new NotImplementedException(), typeof(object));
            var result2 = scope.GetOrAddScopedInstance <object>(scoped => throw new NotImplementedException(), typeof(int));

            //ASSERT
            Assert.Same(instance1, result1);
            Assert.Same(instance2, result2);
        }
Ejemplo n.º 29
0
        public void MethodInject_Scoped_InjectsCorrectDependencies()
        {
            //ARRANGE
            var container = new Container(builder =>
            {
                builder.Register <ITestService10, TestService10>();
            });
            var instance = new MethodInjectionClass();

            //ACT
            Scoped scope = container.BeginScope();

            scope.MethodInject(instance);

            //ASSERT
            Assert.IsType <TestService10>(instance.TestService10);
        }
Ejemplo n.º 30
0
        protected WorkerBase(
            IReceiverClient receiverClient,
            Scoped <IWorkflowLaunchpad> workflowLaunchpad,
            IOptions <AzureServiceBusOptions> options,
            Func <IReceiverClient, Task> disposeReceiverAction,
            ILogger logger)
        {
            ReceiverClient         = receiverClient;
            _workflowLaunchpad     = workflowLaunchpad;
            _disposeReceiverAction = disposeReceiverAction;
            _logger = logger;

            ReceiverClient.RegisterMessageHandler(OnMessageReceived, new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                AutoComplete       = false,
                MaxConcurrentCalls = options.Value.MaxConcurrentCalls
            });
        }
Ejemplo n.º 31
0
 public HomeController(Scoped s)
 {
     _s = s;
 }