public static MethodDefinition Execute(PropertyDefinition property_definition, MethodDefinition notify_method, DependencyMap map)
        {
            log.Trace("\t\t\t\t\tAdding collection notification method for " + property_definition.Name);

            // Create method
            TypeReference return_type = property_definition.Module.Import(typeof (void));
            MethodDefinition collection_notification = new MethodDefinition(property_definition.Name + "CollectionNotification", Mono.Cecil.MethodAttributes.Private | Mono.Cecil.MethodAttributes.HideBySig, return_type);

            // Add parameters
            TypeReference sender_type = property_definition.Module.Import(typeof(object));
            TypeReference args_type = property_definition.Module.Import(typeof(NotifyCollectionChangedEventArgs));

            ParameterDefinition sender = new ParameterDefinition("sender", Mono.Cecil.ParameterAttributes.None, sender_type);
            ParameterDefinition args = new ParameterDefinition("args", Mono.Cecil.ParameterAttributes.None, args_type);

            collection_notification.Parameters.Add(sender);
            collection_notification.Parameters.Add(args);

            // Add notifications for dependent properties
            ILProcessor processor = collection_notification.Body.GetILProcessor();
            foreach (var target in map.GetDependenciesFor(property_definition.Name))
            {
                log.Trace("\t\t\t\t\t\tAdding dependency " + target);
                processor.Emit(OpCodes.Ldarg_0);
                processor.Emit(OpCodes.Ldstr, target);
                processor.Emit(OpCodes.Call, notify_method);
            }
            processor.Emit(OpCodes.Ret);

            // Add method to class
            property_definition.DeclaringType.Methods.Add(collection_notification);
            return collection_notification;
        }
Пример #2
0
        public void ShouldBeAbleToCreateSingletonsThatDependOnOtherSingletons()
        {
            var map = new DependencyMap();
            map.AddSingletonService(typeof(IVehicle), typeof(Vehicle));
            map.AddSingletonService(typeof(IPerson), typeof(Person));

            var compiler = map.ContainerCompiler;
            var outputAssembly = compiler.Compile("MicroContainer", "Hiro.Containers", "Hiro.CompiledContainers", map);
            outputAssembly.Write("singletonOutputAssembly.dll");

            var container = map.CreateContainer();
            var vehicle = container.GetInstance<IVehicle>();
            Assert.IsNotNull(vehicle);

            var person = container.GetInstance<IPerson>();
            Assert.IsNotNull(person);
            for (var i = 0; i < 1000; i++)
            {
                var currentInstance = container.GetInstance<IVehicle>();
                Assert.AreSame(vehicle, currentInstance);

                var driver = currentInstance.Driver;
                Assert.AreSame(driver, person);
            }
        }
Пример #3
0
        public void Load(DependencyMap map)
        {
            _invoked = true;

            // Add a sample implementation
            map.AddService<IList<int>, List<int>>();
        }
        public static void Execute(PropertyDefinition property_definition, MethodDefinition notify_method, DependencyMap map)
        {
            // Check if notifications are already call, if so bail out
            foreach (var instruction in property_definition.SetMethod.Body.Instructions)
            {
                if (instruction.OpCode == OpCodes.Call)
                {
                    var method = instruction.Operand as MethodDefinition;
                    if (method != null && method == notify_method)
                    {
                        log.Trace("\t\t\t\t\tBailing out, notification found in property");
                        return;
                    }
                }
            }

            // Add notifications
            var ret = property_definition.SetMethod.Body.Instructions.Last(i => i.OpCode == OpCodes.Ret);
            ILProcessor processor = property_definition.SetMethod.Body.GetILProcessor();

            // NotifyPropertyChanged(property)
            processor.InsertBefore(ret, processor.Create(OpCodes.Ldarg_0));
            processor.InsertBefore(ret, processor.Create(OpCodes.Ldstr, property_definition.Name));
            processor.InsertBefore(ret, processor.Create(OpCodes.Call, notify_method));

            // Add notifications for dependent properties
            foreach (var target in map.GetDependenciesFor(property_definition.Name))
            {
                log.Trace("\t\t\t\t\tAdding dependency " + target);
                processor.InsertBefore(ret, processor.Create(OpCodes.Ldarg_0));
                processor.InsertBefore(ret, processor.Create(OpCodes.Ldstr, target));
                processor.InsertBefore(ret, processor.Create(OpCodes.Call, notify_method));
            }
        }
Пример #5
0
        public async Task RunAsync(params string[] args)
        {
            _log = LogManager.GetCurrentClassLogger();

            _log.Info("Starting NadekoBot v" + StatsService.BotVersion);

            //create client
            Client = new ShardedDiscordClient(new DiscordSocketConfig
            {
                AudioMode = Discord.Audio.AudioMode.Outgoing,
                MessageCacheSize = 10,
                LogLevel = LogSeverity.Warning,
                TotalShards = Credentials.TotalShards,
                ConnectionTimeout = int.MaxValue
            });

            //initialize Services
            CommandService = new CommandService();
            Localizer = new Localization();
            Google = new GoogleApiService();
            CommandHandler = new CommandHandler(Client, CommandService);
            Stats = new StatsService(Client, CommandHandler);

            //setup DI
            var depMap = new DependencyMap();
            depMap.Add<ILocalization>(Localizer);
            depMap.Add<ShardedDiscordClient>(Client);
            depMap.Add<CommandService>(CommandService);
            depMap.Add<IGoogleApiService>(Google);


            //setup typereaders
            CommandService.AddTypeReader<PermissionAction>(new PermissionActionTypeReader());
            CommandService.AddTypeReader<Command>(new CommandTypeReader());
            CommandService.AddTypeReader<Module>(new ModuleTypeReader());
            CommandService.AddTypeReader<IGuild>(new GuildTypeReader());

            //connect
            await Client.LoginAsync(TokenType.Bot, Credentials.Token).ConfigureAwait(false);
            await Client.ConnectAsync().ConfigureAwait(false);
            await Client.DownloadAllUsersAsync().ConfigureAwait(false);

            _log.Info("Connected");

            //load commands and prefixes
            using (var uow = DbHandler.UnitOfWork())
            {
                ModulePrefixes = new ConcurrentDictionary<string, string>(uow.BotConfig.GetOrCreate().ModulePrefixes.ToDictionary(m => m.ModuleName, m => m.Prefix));
            }
            // start handling messages received in commandhandler
            await CommandHandler.StartHandling().ConfigureAwait(false);

            await CommandService.LoadAssembly(this.GetType().GetTypeInfo().Assembly, depMap).ConfigureAwait(false);
#if !GLOBAL_NADEKO
            await CommandService.Load(new Music(Localizer, CommandService, Client, Google)).ConfigureAwait(false);
#endif
            Ready = true;
            Console.WriteLine(await Stats.Print().ConfigureAwait(false));
        }
Пример #6
0
        public void ShouldBeAbleToRegisterAnonymousServicesWithDependencyMapUsingGenerics()
        {
            var dependencyMap = new DependencyMap();
            dependencyMap.AddService<IVehicle, Vehicle>();

            Assert.IsTrue(dependencyMap.Contains(new Dependency(typeof(IVehicle))));
            Assert.IsTrue(dependencyMap.Contains(typeof(IVehicle)));
        }
 public void Circle()
 {
     DependencyMap<string> map = new DependencyMap<string>();
     map.Add("A", "B");
     map.Add("B", "C");
     map.Add("C", "A");
     map.SortDependencies();
 }
Пример #8
0
        public void ShouldBeAbleToInstantiateGenericTypes()
        {
            var map = new DependencyMap();
            map.AddService(typeof(IList<>), typeof(List<>));

            var container = map.CreateContainer();
            var list = container.GetInstance<IList<int>>();
            Assert.IsNotNull(list);
        }
        public override void Prepare()
        {
            var map = new DependencyMap();
            RegisterBasic(map);
            
            RegisterPropertyInjection(map);

            this.container = map.CreateContainer();
        }
        public void ShouldBeAbleToUseGenericsToGetAnonymousServiceInstances()
        {
            var map = new DependencyMap();
            map.AddService(typeof(IPerson), typeof(Person));

            var container = map.CreateContainer();
            IPerson person = container.GetInstance<IPerson>();

            Assert.IsNotNull(person);
        }
Пример #11
0
        public override void Prepare()
        {
            var map = new DependencyMap();

            RegisterDummies(map);
            RegisterStandard(map);
            RegisterComplex(map);

            this.container = map.CreateContainer();
        }
Пример #12
0
        public void ShouldBeAbleToAddItemsToDependencyMap()
        {
            var ctor = typeof(Vehicle).GetConstructor(new Type[0]);
            var dependency = new Dependency(typeof(IVehicle), string.Empty);
            var constructorImplementation = new ConstructorCall(ctor);

            var dependencyMap = new DependencyMap();
            dependencyMap.AddService(dependency, constructorImplementation);
            Assert.IsTrue(dependencyMap.Contains(dependency));
        }
Пример #13
0
 private static void RegisterComplex(DependencyMap map)
 {
     map.AddSingletonService<IFirstService, FirstService>();
     map.AddSingletonService<ISecondService, SecondService>();
     map.AddSingletonService<IThirdService, ThirdService>();
     map.AddService<ISubObjectOne, SubObjectOne>();
     map.AddService<ISubObjectTwo, SubObjectTwo>();
     map.AddService<ISubObjectThree, SubObjectThree>();
     map.AddService<IComplex, Complex>();
 }
Пример #14
0
        public override void Prepare()
        {
            var map = new DependencyMap();

            map.AddSingletonService<ISingleton, Singleton>();
            map.AddService<ITransient, Transient>();
            map.AddService<ICombined, Combined>();

            this.container = map.CreateContainer();
        }
        public void WorstCase()
        {
            DependencyMap<string> map = new DependencyMap<string>();
            map.Add("A", "B");
            map.Add("B", "C");
            map.Add("C", "D");
            map.Add("D", "E");
            map.Add("E", null);

            CheckSort("EDCBA", map);
        }
        public void DegenerateCase()
        {
            DependencyMap<string> map = new DependencyMap<string>();
            map.Add("A", null);
            map.Add("B", null);
            map.Add("C", null);
            map.Add("D", null);
            map.Add("E", null);

            CheckSort("ABCDE", map);
        }
Пример #17
0
        public void ShouldBeAbleToGetCurrentListOfDependencies()
        {
            var map = new DependencyMap();
            for (int i = 0; i < 10; i++)
            {
                var dependency = new Mock<IDependency>();
                var implementation = new Mock<IImplementation>();

                map.AddService(dependency.Object, implementation.Object);
                Assert.IsTrue(map.Dependencies.Contains(dependency.Object));
            }
        }
Пример #18
0
 private static void RegisterStandard(DependencyMap map)
 {
     map.AddSingletonService<ISingleton1, Singleton1>();
     map.AddSingletonService<ISingleton2, Singleton2>();
     map.AddSingletonService<ISingleton3, Singleton3>();
     map.AddService<ITransient1, Transient1>();
     map.AddService<ITransient2, Transient2>();
     map.AddService<ITransient3, Transient3>();
     map.AddService<ICombined1, Combined1>();
     map.AddService<ICombined2, Combined2>();
     map.AddService<ICombined3, Combined3>();
 }
        public void Typical()
        {
            DependencyMap<string> map = new DependencyMap<string>();
            map.Add("A", "C");  // Forward reference
            map.Add("B", "E");  // Forward reference
            map.Add("D", null); // No dependency
            map.Add("C", "B");  // Backward reference
            map.Add("E", null); // No dependency
            map.Add("F", "G");  // Dependent on something outside map

            CheckSort("DEFBCA", map);
        }
Пример #20
0
 private static void RegisterDummies(DependencyMap map)
 {
     map.AddService<IDummyOne, DummyOne>();
     map.AddService<IDummyTwo, DummyTwo>();
     map.AddService<IDummyThree, DummyThree>();
     map.AddService<IDummyFour, DummyFour>();
     map.AddService<IDummyFive, DummyFive>();
     map.AddService<IDummySix, DummySix>();
     map.AddService<IDummySeven, DummySeven>();
     map.AddService<IDummyEight, DummyEight>();
     map.AddService<IDummyNine, DummyNine>();
     map.AddService<IDummyTen, DummyTen>();
 }
Пример #21
0
        public void ShouldBeAbleToCombineDependencyMaps()
        {
            var firstMap = new DependencyMap();
            var secondMap = new DependencyMap();

            firstMap.AddService(typeof(IPerson), typeof(Person));
            secondMap.AddService(typeof(IVehicle), typeof(Vehicle));

            DependencyMap combinedMap = firstMap + secondMap;
            var container = combinedMap.CreateContainer();
            Assert.IsNotNull(container.GetInstance<IVehicle>());
            Assert.IsNotNull(container.GetInstance<IPerson>());
        }
Пример #22
0
        public void ShouldBeAbleToAddTypedFunctorToDependencyMap()
        {
            var expectedInstance = new Foo();
            Func<IMicroContainer, IFoo> functor = c => expectedInstance;

            var map = new DependencyMap();
            map.AddService(functor);

            var container = map.CreateContainer();
            var foo = container.GetInstance<IFoo>();

            Assert.AreSame(expectedInstance, foo);
        }
        public void ShouldBeAbleToAddExistingServiceInstanceToContainer()
        {
            var map = new DependencyMap();
            var person = new Person();

            // Create a blank container
            var container = map.CreateContainer();

            container.AddService<IPerson>(null, person);

            // The container should return the added instance
            var result = container.GetInstance<IPerson>();
            Assert.AreSame(person, result);
        }
Пример #24
0
        public Hiro()
        {
            var map = new DependencyMap();
            map.AddSingletonService<Game, Game>();
            map.AddService<Player, Player>();
            map.AddService<Gun, Gun>();
            map.AddService<Bullet, Bullet>();

            Func<IMicroContainer, Bullet> createBullet = c => c.GetInstance<Bullet>();
            Func<IMicroContainer, Func<Bullet>> createBulletFunctor = c => () => createBullet(c);
            map.AddService(createBulletFunctor);

            container = map.CreateContainer();
        }
Пример #25
0
        public void ShouldBeAbleToAddNamedUntypedFunctorToDependencyMap()
        {
            var expectedInstance = new Foo();
            Func<IMicroContainer, object> functor = c => expectedInstance;

            var serviceType = typeof(IFoo);
            var map = new DependencyMap();
            map.AddService("myFoo", serviceType, functor);

            var container = map.CreateContainer();
            var foo = container.GetInstance<IFoo>("myFoo");
            Assert.IsNotNull(foo);
            Assert.AreSame(expectedInstance, foo);
        }
Пример #26
0
        public void ShouldBeAbleToInjectGenericConstructor()
        {
            var map = new DependencyMap();
            map.AddService<UnitOfWorkScopeBase<UserUnitOfWork>,
            SimpleUnitOfWorkScope<UserUnitOfWork>>();

            map.AddSingletonService<LightSpeedContext<UserUnitOfWork>,
            LightSpeedContext<UserUnitOfWork>>();

            var container = map.CreateContainer();
            var service = container.GetInstance<UnitOfWorkScopeBase<UserUnitOfWork>>();

            Assert.IsNotNull(service);
        }
Пример #27
0
        public void ShouldBeAbleToCombineDependencyMaps()
        {
            var firstMap  = new DependencyMap();
            var secondMap = new DependencyMap();

            firstMap.AddService(typeof(IPerson), typeof(Person));
            secondMap.AddService(typeof(IVehicle), typeof(Vehicle));

            DependencyMap combinedMap = firstMap + secondMap;
            var           container   = combinedMap.CreateContainer();

            Assert.IsNotNull(container.GetInstance <IVehicle>());
            Assert.IsNotNull(container.GetInstance <IPerson>());
        }
        private static void ConfigureClass(Type type, IRegistry registry, FireOptions fireOption, DependencyMap dependencyMap)
        {
            var inst = new LooseConstructorInstance(context =>
            {
                var ctorArgs = type
                    .GetGreediestCtor()
                    .GetParameters()
                    .Select(p => context.GetInstance(p.ParameterType));

                return Notifiable.MakeForClass(type, fireOption, ctorArgs.ToArray(), new ProxyGenerator(), dependencyMap);
            });

            registry.For(type).Use(inst);
        }
Пример #29
0
        public void ShouldBeAbleToAddNamedTypedFunctorToDependencyMap()
        {
            var expectedInstance = new Foo();
            Func <IMicroContainer, IFoo> functor = c => expectedInstance;

            var map = new DependencyMap();

            map.AddService("myFoo", functor);

            var container = map.CreateContainer();
            var foo       = container.GetInstance <IFoo>("myFoo");

            Assert.AreSame(expectedInstance, foo);
        }
Пример #30
0
        public void DependencyMap_Ctor2_Asbtract_Test()
        {
            //arrange
            Type                type = typeof(abs_foo);
            IDependencyMap      dependencyMap;
            Mock <IDIContainer> mockContainer = new Mock <IDIContainer>();

            //act
            dependencyMap = new DependencyMap(mockContainer.Object, type, InstanceType.Local);

            //assert
            Assert.AreEqual(type.GetDependencyId(), dependencyMap.SourceDependencyId);
            Assert.AreEqual(true, dependencyMap.IsAbstractOrInterface);
            Assert.IsNull(dependencyMap.PrimaryDependencyHolder);
        }
Пример #31
0
        /// <summary>
        /// Adds a named service to the dependency map.
        /// </summary>
        /// <remarks>This service will be created once per web session.</remarks>
        /// <param name="map">The target dependency map.</param>
        /// <param name="serviceName">The service name.</param>
        /// <param name="serviceType">The service type.</param>
        /// <param name="implementingType">The implementing type.</param>
        public static void AddPerSessionService(this DependencyMap map, string serviceName, Type serviceType, Type implementingType)
        {
            // Add the SessionCache by default
            if (!map.Contains(typeof(ICache)))
            {
                map.AddService <ICache, SessionCache>();
            }

            // The cached instantiation class will use the cache in the container
            // to cache service instances
            var dependency     = new Dependency(serviceType, serviceName);
            var implementation = new CachedInstantiation(new TransientType(implementingType, map, new ConstructorResolver()));

            map.AddService(dependency, implementation);
        }
Пример #32
0
        private void RemoveNonSourcesFromRoots(IList roots, DependencyMap precedents)
        {
            var arr = new Reference[roots.Count];

            roots.CopyTo(arr, 0);

            for (int i = 0; i <= arr.Length - 1; i++)
            {
                Reference root = arr[i];
                if (precedents.ContainsTail(root))
                {
                    roots.Remove(root);
                }
            }
        }
Пример #33
0
        public void ShouldBeAbleToInjectGenericConstructor()
        {
            var map = new DependencyMap();

            map.AddService <UnitOfWorkScopeBase <UserUnitOfWork>,
                            SimpleUnitOfWorkScope <UserUnitOfWork> >();

            map.AddSingletonService <LightSpeedContext <UserUnitOfWork>,
                                     LightSpeedContext <UserUnitOfWork> >();

            var container = map.CreateContainer();
            var service   = container.GetInstance <UnitOfWorkScopeBase <UserUnitOfWork> >();

            Assert.IsNotNull(service);
        }
Пример #34
0
        public void ShouldBeAbleToInstantiateNamedGenericType()
        {
            var map = new DependencyMap();
            map.AddService("List", typeof(IEnumerable<>), typeof(List<>));
            map.AddService("Queue", typeof(IEnumerable<>), typeof(Queue<>));

            var container = map.CreateContainer();
            var list = container.GetInstance<IEnumerable<int>>("List");
            Assert.IsNotNull(list);

            var queue = container.GetInstance<IEnumerable<int>>("Queue");
            Assert.IsNotNull(queue);

            Assert.IsFalse(queue.GetType() != list.GetType());
        }
Пример #35
0
        public void ShouldUseConstructorParameterNameToInjectNamedServiceInstanceIfTheNamedServiceExists()
        {
            var map = new DependencyMap();

            map.AddService <IVehicle, Vehicle>("Vehicle");
            map.AddService <IVehicle, Truck>("Truck");
            map.AddService <Garage, Garage>();

            var container = map.CreateContainer();

            var garage = container.GetInstance <Garage>();

            Assert.IsNotNull(garage.Vehicle);
            Assert.IsInstanceOfType(typeof(Vehicle), garage.Vehicle);
        }
Пример #36
0
        public void ShouldBeAbleToReturnTheSameSingletonInstance()
        {
            var map = new DependencyMap();

            map.AddSingletonService(typeof(IPerson), typeof(Person));

            var container = map.CreateContainer();
            var result    = container.GetInstance(typeof(IPerson), null);

            for (var i = 0; i < 100; i++)
            {
                var currentResult = container.GetInstance(typeof(IPerson), null);
                Assert.AreSame(result, currentResult);
            }
        }
Пример #37
0
        public void ShouldInjectPropertyIfDependencyMapHasAPropertyInjectorAssignedToTheInjectorProperty()
        {
            var map = new DependencyMap();
            map.Injector = new PropertyInjector();

            map.AddService<IVehicle, Vehicle>();
            map.AddService<IPerson, Person>();

            var container = map.CreateContainer();

            var result = (IVehicle)container.GetInstance(typeof(IVehicle), null);
            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Driver);
            Assert.IsTrue(result.Driver is Person);
        }
Пример #38
0
        public void ShouldBeAbleToAddExistingServiceInstanceToContainer()
        {
            var map    = new DependencyMap();
            var person = new Person();

            // Create a blank container
            var container = map.CreateContainer();

            container.AddService <IPerson>(null, person);

            // The container should return the added instance
            var result = container.GetInstance <IPerson>();

            Assert.AreSame(person, result);
        }
Пример #39
0
        public void ShouldBeAbleToInstantiateGenericSingletonTypes()
        {
            var map = new DependencyMap();

            map.AddSingletonService(typeof(IList <>), typeof(List <>));

            var container = map.CreateContainer();
            var list      = container.GetInstance <IList <int> >();

            Assert.IsNotNull(list);

            var otherList = container.GetInstance <IList <int> >();

            Assert.AreSame(list, otherList);
        }
Пример #40
0
        public void ShouldBeAbleToCompileContainerUsingATypeWithMultipleConstructors()
        {
            var map = new DependencyMap();

            map.AddService(typeof(IVehicle), typeof(Vehicle));
            map.AddService(typeof(IPerson), typeof(Person));

            var container = Compile(map);
            var result    = container.GetInstance(typeof(IVehicle), null);

            var vehicle = (IVehicle)result;

            Assert.IsNotNull(vehicle);
            Assert.IsNotNull(vehicle.Driver);
        }
Пример #41
0
        public async Task Start()
        {
            // As we are not using 4.6 we must include the Discord.Net WebSocketProvider.
            client = new DiscordSocketClient(new DiscordSocketConfig {
                WebSocketProvider = Discord.Net.Providers.WS4Net.WS4NetProvider.Instance,
                LogLevel          = LogSeverity.Verbose
            });
            // Writes detailed log to the console
            client.Log += (l)
                          => Task.Run(()
                                      => Console.WriteLine($"[{l.Severity}] {l.Source}: {l.Exception?.ToString() ?? l.Message}"));

            // Variable for token
            var token = "MjY0MjAwODI2NDI2MzU5ODA4.C3NZWg.hLb2Z8U66zcef7fgC43yAra6Ydo";

            // Use token to login, and then use asyncconnect to connect to discord
            await client.LoginAsync(TokenType.Bot, token);

            await client.ConnectAsync();

            // Create a new dependency map
            var map = new DependencyMap();

            map.Add(client);

            // Recall command handler and add the dependency map to it
            handler = new CommandHandler();
            await handler.Install(map);

            // Hooking into events

            client.UserJoined += async(e) =>
            {
                try
                {
                    ulong channelid = 266188297339011082;
                    e.Discord.GetChannel(channelid);
                    Console.WriteLine("Channel Found");
                }
                catch
                {
                    Console.WriteLine("Channel not found, or error with code");
                }
            };

            // Block the closing of the program until it is closed
            await Task.Delay(-1);
        }
Пример #42
0
        public Hiro()
        {
            var map = new DependencyMap();

            map.AddSingletonService <Game, Game>();
            map.AddService <Player, Player>();
            map.AddService <Gun, Gun>();
            map.AddService <Bullet, Bullet>();

            Func <IMicroContainer, Bullet>         createBullet        = c => c.GetInstance <Bullet>();
            Func <IMicroContainer, Func <Bullet> > createBulletFunctor = c => () => createBullet(c);

            map.AddService(createBulletFunctor);

            container = map.CreateContainer();
        }
Пример #43
0
        public void ShouldBeAbleToAddUntypedFunctorToDependencyMap()
        {
            var expectedInstance = new Foo();
            Func <IMicroContainer, object> functor = c => expectedInstance;

            var serviceType = typeof(IFoo);
            var map         = new DependencyMap();

            map.AddService(serviceType, functor);

            var container = map.CreateContainer();
            var foo       = container.GetInstance <IFoo>();

            Assert.IsNotNull(foo);
            Assert.AreSame(expectedInstance, foo);
        }
Пример #44
0
        public void InnerDependenciesSucceeds()
        {
            DependencyMap injector = new DependencyMap();

            injector.Register <IInterface, AnotherClass>();
            var actualClass = (AnotherClass)injector.Resolve(typeof(IInterface));

            AssertResolution(actualClass, typeof(AnotherClass));
            Assert.True(actualClass.Blah == null);

            injector.Register <ITestInterface, TestClass>();
            actualClass = (AnotherClass)injector.Resolve(typeof(IInterface));
            Assert.True(
                actualClass.Blah.GetType() == typeof(TestClass),
                $"Expected {typeof(TestClass).Name}\nWas {actualClass.Blah.GetType().Name}"
                );
        }
        public async Task Start()
        {
            client = new DiscordSocketClient();

            await client.LoginAsync(TokenType.Bot, "TOKEN HERE");

            await client.ConnectAsync();

            var map = new DependencyMap();

            map.Add(client);

            handler = new CommandHandler();
            await handler.Install(map);

            await Task.Delay(-1);
        }
Пример #46
0
        public void DependencyResolutionSucceeds()
        {
            DependencyMap injector = new DependencyMap();

            injector.Register <ITestInterface, TestClass>();
            injector.Register(typeof(AnotherClass));
            object actualClass  = injector.Resolve(typeof(ITestInterface));
            object anotherClass = injector.Resolve(typeof(AnotherClass));

            AssertResolution(actualClass, typeof(TestClass));
            AssertResolution(anotherClass, typeof(AnotherClass));

            actualClass  = injector.Resolve <ITestInterface>();
            anotherClass = injector.Resolve <AnotherClass>();
            AssertResolution(actualClass, typeof(TestClass));
            AssertResolution(anotherClass, typeof(AnotherClass));
        }
Пример #47
0
    public async Task Start()
    {
        client   = new DiscordSocketClient();
        commands = new CommandService();

        string token = "bot token here";

        map = new DependencyMap();

        await InstallCommands();

        await client.LoginAsync(TokenType.Bot, token);

        await client.ConnectAsync();

        await Task.Delay(-1);
    }
Пример #48
0
        public void ShouldInjectPropertyIfDependencyMapHasAPropertyInjectorAssignedToTheInjectorProperty()
        {
            var map = new DependencyMap();

            map.Injector = new PropertyInjector();

            map.AddService <IVehicle, Vehicle>();
            map.AddService <IPerson, Person>();

            var container = map.CreateContainer();

            var result = (IVehicle)container.GetInstance(typeof(IVehicle), null);

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Driver);
            Assert.IsTrue(result.Driver is Person);
        }
Пример #49
0
        public async Task RunAsync(params string[] args)
        {
            PrettyConsole.NewLine("===   DEA   ===");
            PrettyConsole.NewLine();

            Client = new DiscordSocketClient(new DiscordSocketConfig()
            {
                LogLevel         = LogSeverity.Error,
                MessageCacheSize = 10,
                TotalShards      = Credentials.ShardCount,
                //AlwaysDownloadUsers = true,
            });

            Client.Log += (l)
                          => Task.Run(()
                                      => PrettyConsole.Log(l.Severity, l.Source, l.Exception?.ToString() ?? l.Message));

            CommandService = new CommandService(new CommandServiceConfig()
            {
                CaseSensitiveCommands = false,
                DefaultRunMode        = RunMode.Sync
            });

            var sw = Stopwatch.StartNew();
            //Connection
            await Client.LoginAsync(TokenType.Bot, Credentials.Token).ConfigureAwait(false);

            await Client.StartAsync().ConfigureAwait(false);

            //await Client.DownloadAllUsersAsync().ConfigureAwait(false);
            sw.Stop();
            PrettyConsole.Log(LogSeverity.Info, "Successfully connected", $"Elapsed time: {sw.Elapsed.TotalSeconds.ToString()} seconds.");

            var Map = new DependencyMap();

            ConfigureServices(Map);
            await new MessageRecieved().InitializeAsync(Client, Map);
            new Ready(Client);
            PrettyConsole.Log(LogSeverity.Info, "Events and mapping successfully initialized", $"Client ready.");

            using (var db = new DEAContext())
            {
                await db.Database.EnsureCreatedAsync();
            }
            PrettyConsole.Log(LogSeverity.Info, "Database creation ensured", $"Ready for use.");
        }
Пример #50
0
        public void ShouldInjectDefaultServiceImplementationIntoTargetProperty()
        {
            var map = new DependencyMap();

            var dependency = new Dependency(typeof(IVehicle));
            var injector = new PropertyInjectionCall(new TransientType(typeof(Vehicle), map, new ConstructorResolver()));
            map.AddService(dependency, injector);

            map.AddService(typeof(IPerson), typeof(Person));

            var container = map.CreateContainer();

            var result = (IVehicle)container.GetInstance(typeof(IVehicle), null);
            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Driver);
            Assert.IsTrue(result.Driver is Person);
        }
Пример #51
0
        public void ShouldCallInitializeOnSingletonTypeThatImplementsIInitializeOnceAndOnlyOnce()
        {
            var map = new DependencyMap();

            map.AddSingletonService <IInitialize, SampleInitialize>();

            var container = map.CreateContainer();
            var result    = (SampleInitialize)container.GetInstance <IInitialize>();

            for (var i = 0; i < 100; i++)
            {
                result = (SampleInitialize)container.GetInstance <IInitialize>();
            }

            Assert.AreSame(container, result.Container);
            Assert.IsTrue(result.NumberOfTimesInitialized == 1);
        }
Пример #52
0
        public async Task Run(string[] args)
        {
            // Init vars
            CTS = new CancellationTokenSource();
            CT  = CTS.Token;

            // Setup objects
            _client = new DiscordSocketClient(new DiscordSocketConfig()
            {
                AlwaysDownloadUsers = true,
                LogLevel            = LogSeverity.Debug,
                MessageCacheSize    = 250
            });

            // Setup event handlers
            _client.Log         += ClientLog;
            _client.JoinedGuild += ClientJoinGuild;

            // Login and start bot
            // For a locally running bot, it's fine to use an environment variable, for ease of use
            // If you distribute your bot, using a config.json is recommended.
            // Since we will showcase more options, we will use a config.json
            // To use an env variable, you can do something like this: Properties.Resources.ResourceManager.GetString("BOT_TOKEN")
            // Our ConfigManager is static, see ConfigManager.cs
            // For your config.json file, make sure Copy to output directory is set to Always
            await ConfigManager.Read();

            // First login, then start
            // Similar order reverse: StopAsync, LogoutAsync
            await _client.LoginAsync(TokenType.Bot, ConfigManager.properties.Token);

            await _client.StartAsync();

            var map = new DependencyMap();

            map.Add(_client);

            handler = new CommandHandler();
            await handler.Install(map);

            Console.Title = "Example Bot - " + ConfigManager.properties.Version;

            // Block program until it's closed or task is canceled
            await Task.Delay(-1, CT);
        }
Пример #53
0
        private async Task DoBotStuff()
        {
            map      = new DependencyMap();
            commands = new CommandService();
            client   = new DiscordSocketClient();

            await ConfigureEventHandlers();
            await InstallCommands();

            Console.WriteLine("Logging In");
            await client.LoginAsync(Discord.TokenType.Bot, Constants.DiscordToken);

            Console.WriteLine("Logged In");
            Console.WriteLine("Connecting");
            await client.StartAsync();

            Console.WriteLine("Connected. Awaiting Instruction");
        }
Пример #54
0
        public void ShouldReturnImplementationsFromDependencyMapFromImplementationsThatHaveNoMissingDependencies()
        {
            var map            = new DependencyMap();
            var dependency     = new Dependency(typeof(IVehicle), string.Empty);
            var implementation = new Mock <IImplementation>();

            implementation.Expect(impl => impl.GetMissingDependencies(map)).Returns(new IDependency[0]);

            bool addIncompleteImplementations = false;

            map.AddService(dependency, implementation.Object);
            var results = map.GetImplementations(dependency, addIncompleteImplementations);

            Assert.IsTrue(results.Count() > 0);
            Assert.IsTrue(results.Contains(implementation.Object));

            implementation.VerifyAll();
        }
Пример #55
0
        public void ShouldBeAbleToInstantiateNamedGenericType()
        {
            var map = new DependencyMap();

            map.AddService("List", typeof(IEnumerable <>), typeof(List <>));
            map.AddService("Queue", typeof(IEnumerable <>), typeof(Queue <>));

            var container = map.CreateContainer();
            var list      = container.GetInstance <IEnumerable <int> >("List");

            Assert.IsNotNull(list);

            var queue = container.GetInstance <IEnumerable <int> >("Queue");

            Assert.IsNotNull(queue);

            Assert.IsFalse(queue.GetType() != list.GetType());
        }
Пример #56
0
        /// <summary>
        /// Creates a new Cell
        /// </summary>
        public Cell()
        {
            //GUI
            InitializeComponent();
            BorderBrush                = new SolidColorBrush(Colors.Black);
            BorderThickness            = new Thickness(0.25);
            CellText.MouseDoubleClick += Cell_MouseDoubleClick;
            CellText.LostFocus        += CellText_LostFocus;
            CellText.GotFocus         += CellText_GotFocus;
            CellText.KeyDown          += CellText_KeyDown;
            Focusable = true;

            //!GUI
            CellFormula = "";
            CellDisplay = "";

            Dependencies = new DependencyMap(this);
        }
Пример #57
0
        private async Task HandleCommand(SocketMessage s)
        {
            // Don't handle the command if it is a system message
            var msg = s as SocketUserMessage;

            if (msg == null)                                                // Check if the received message is from a user.
            {
                return;
            }

            var map = new DependencyMap();                                  // Create a new dependecy map.

            map.Add(_cmds);                                                 // Add the command service to the dependency map

            map.Add(_timer);                                                // Add our services to the dependency map

            var context = new SocketCommandContext(_client, msg);           // Create a new command context.

            int argPos = 0;                                                 // Check if the message has either a string or mention prefix.

            if (msg.HasStringPrefix(BotConfiguration.Load().Prefix, ref argPos) ||
                msg.HasMentionPrefix(_client.CurrentUser, ref argPos))
            {
                if (_logcommands)                    // only if logging is enabled in config and it's a bot message
                {
                    try
                    {
                        _da.LogCommand(context.Guild.Name, msg.Channel.Name, msg.Author.Username, msg.Content, msg.Timestamp.ToLocalTime().ToString());
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }

                // Try and execute a command with the given context.
                var result = await _cmds.ExecuteAsync(context, argPos, map);

                if (!result.IsSuccess)                                          // If execution failed, reply with the error message.
                {
                    await context.Channel.SendMessageAsync(result.ToString());
                }
            }
        }
        public HiroUseCase()
        {
            var map = new DependencyMap();

            map.AddService(typeof(IWebService), typeof(WebService));
            map.AddService(typeof(IAuthenticator), typeof(Authenticator));
            map.AddService(typeof(IStockQuote), typeof(StockQuote));
            map.AddService(typeof(IDatabase), typeof(Database));
            map.AddService(typeof(IErrorHandler), typeof(ErrorHandler));
            map.AddService(typeof(ILogger), typeof(Logger));

            IContainerCompiler compiler = new ContainerCompiler();
            var assembly = compiler.Compile(map);

            var loadedAssembly = assembly.ToAssembly();
            var containerType  = loadedAssembly.GetTypes()[0];

            container = (IMicroContainer)Activator.CreateInstance(containerType);
        }
Пример #59
0
        public void ShouldCallGetInstanceMethodOnNextContainer()
        {
            var map       = new DependencyMap();
            var container = map.CreateContainer();

            Assert.IsNotNull(container);

            var mockContainer = new Mock <IMicroContainer>();

            mockContainer.Expect(m => m.GetInstance(It.IsAny <System.Type>(), It.IsAny <string>())).Returns(42);
            container.NextContainer = mockContainer.Object;

            Assert.AreSame(container.NextContainer, mockContainer.Object);

            var result = container.GetInstance(typeof(int), "abcdefg");

            Assert.AreEqual(42, result);
            mockContainer.VerifyAll();
        }
Пример #60
0
        public void ShouldBeAbleToCompileContainerWithParameterlessConstructor()
        {
            var targetConstructor = typeof(Vehicle).GetConstructor(new System.Type[0]);

            var dependency     = new Dependency(typeof(IVehicle), string.Empty);
            var implementation = new ConstructorCall(targetConstructor);

            var map = new DependencyMap();

            map.AddService(dependency, implementation);

            var container = Compile(map);

            Assert.IsTrue(container.Contains(typeof(IVehicle), string.Empty));

            var result = container.GetInstance(typeof(IVehicle), string.Empty);

            Assert.IsNotNull(result);
        }