public void AutofacCanLoadConfiguration()
        {
            //_autofacContainer.AddDependencyDemandBuilder(new LoadFromConfiguration());
            _autofacContainer.AddDemandsFromAssemblyOf <LoadFromPersistenceConfig>();

            IDependencyResolver resolver = _autofacContainer.Build();

            CheckResolvedProvider(resolver.Resolve <IPersistenceMappingGroup>("nhibernate-01"),
                                  typeof(Framework.Persistence.NHibernate.Reader),
                                  typeof(Framework.Persistence.NHibernate.ReadWriter));
        }
Пример #2
0
        private void RegisterDependencies()
        {
            //Register each DP as the type it selected to expose
            foreach (DependencyTypePair dtp in TypePairs)
            {
                AutofacContainerBuilder.RegisterInstance(dtp.Behaviour)
                .As(dtp.SelectedType);
            }

            //the IoC container visits each dependency registeration object
            //This allows the registeration logic to be handled differently
            foreach (var nbd in NonBehaviourDependencies)
            {
                nbd.Register(AutofacContainerBuilder);
            }

            //Register the GameObjectFactory and ComponentFactory too
            AutofacContainerBuilder.Register(context => new DefaultGameObjectFactory(context.Resolve <IComponentContext>(), new DefaultInjectionStrategy()))
            .As <IGameObjectFactory>()
            .SingleInstance();

            AutofacContainerBuilder.Register(context => new DefaultGameObjectComponentAttachmentFactory(context.Resolve <IComponentContext>(), new DefaultInjectionStrategy()))
            .As <IGameObjectComponentAttachmentFactory>()
            .SingleInstance();

            AutofacContainerBuilder.Register(context => new DefaultManualInjectionStrategy(context.Resolve <IComponentContext>()))
            .As <IManualInjectionStrategy>()
            .SingleInstance();

            BuiltContainerResolver = AutofacContainerBuilder.Build();
        }
Пример #3
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var builder = new AutofacContainerBuilder();
            var providerConfiguration = Configuration.GetSection("Vedaantees").Get <ProviderConfiguration>();

            providerConfiguration.ModulesFolder = string.Empty;

            var bootstrapper = new ProviderBootstrapper(builder, providerConfiguration);

            bootstrapper.Load(_env);

            services.AddMvc().AddRazorOptions(options =>
            {
                options.ViewLocationFormats.Clear();
                options.ViewLocationFormats.Add("/Presentation/{0}.cshtml");
            });
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(IdentityServerConfiguration.GetIdentityResources())
            .AddInMemoryApiResources(IdentityServerConfiguration.GetApiResources())
            .AddInMemoryClients(IdentityServerConfiguration.GetClients(Configuration.GetSection("Clients").Get <List <string> >()));

            services.AddTransient <IResourceOwnerPasswordValidator, UserStore>()
            .AddTransient <IProfileService, UserStore>();

            builder.RegisterInstance <IConfiguration>(Configuration);
            builder.Builder.Populate(services);
            ApplicationContainer = builder.Build();
            bootstrapper.InitializeFramework(ApplicationContainer);
            return(new AutofacServiceProvider(ApplicationContainer));
        }
        public static Autofac.IContainer BuildContainer()
        {
            var containerBuilder = new AutofacContainerBuilder();

            //var bootstrapper = new ProviderBootstrapper(containerBuilder); //MockBuilder.BuildConfiguration()
            //bootstrapper.Load();
            return(containerBuilder.Build());
        }
Пример #5
0
        public void ResolveInstance()
        {
            var containerBuilder = new AutofacContainerBuilder();

            containerBuilder.RegisterInstance <ITestInterfaceForContainer>(new TestInterfaceForContainer());
            var container = containerBuilder.Build();
            var instance  = container.Resolve <ITestInterfaceForContainer>();

            Assert.AreEqual(instance.GetType(), typeof(TestInterfaceForContainer));
        }
Пример #6
0
        public void ResolveTransient()
        {
            var containerBuilder = new AutofacContainerBuilder();

            containerBuilder.RegisterTransient <ITestGenericInterface <ITestInterfaceForContainer>, TestGeneric>();
            var container = containerBuilder.Build();
            var instance  = container.Resolve <ITestGenericInterface <ITestInterfaceForContainer> >();

            Assert.AreEqual(instance.GetType(), typeof(TestGeneric));
        }
Пример #7
0
        public void ResolveByFunc()
        {
            var containerBuilder = new AutofacContainerBuilder();

            containerBuilder.RegisterPerRequest <ITestInterfaceForContainer, TestInterfaceForContainer>(context => new TestInterfaceForContainer());
            var container = containerBuilder.Build();
            var instance  = container.Resolve <ITestInterfaceForContainer>();

            Assert.AreEqual(instance.GetType(), typeof(TestInterfaceForContainer));
        }
Пример #8
0
        public void ResolveByMultipleFuncInstance()
        {
            var containerBuilder = new AutofacContainerBuilder();

            containerBuilder.RegisterSingleton <ITestInterfaceForContainer, IOtherTestInterfaceForContainer, TestInterfaceForContainer>(context => new TestInterfaceForContainer());
            var container = containerBuilder.Build();
            var instance  = container.Resolve <IOtherTestInterfaceForContainer>();

            Assert.AreEqual(instance.GetType(), typeof(TestInterfaceForContainer));
        }
Пример #9
0
        public void ResolveTypesByThierInterfaces()
        {
            var containerBuilder = new AutofacContainerBuilder();

            containerBuilder.RegisterTypesByThierInterfaces(GetType().Assembly);
            var container = containerBuilder.Build();
            var instance  = container.Resolve <ITestGenericInterface <ITestInterfaceForContainer> >();

            Assert.AreEqual(instance.GetType(), typeof(TestGeneric));
        }
        public void AutofacContainerBuilder_ForFactoryTests_ForFactory_RegisteredTypeComesFromDelegate()
        {
            //Arrange
            var autofacContainerBuilder = new AutofacContainerBuilder();

            //Act
            autofacContainerBuilder.ForFactory(x => new Foo());
            var resolver = autofacContainerBuilder.Build();

            //Assert
            Assert.IsNotNull(resolver.Resolve <Foo>());
        }
        public void AutofacContainerBuilderTests_ForInstanceOfType_RegisteredTypeResoslvable()
        {
            //Arrange
            var autofacContainerBuilder = new AutofacContainerBuilder();

            //Act
            autofacContainerBuilder.ForInstanceOfType(new Foo());
            var resolver = autofacContainerBuilder.Build();

            //Assert
            Assert.IsNotNull(resolver.Resolve <Foo>());
        }
        public void AutofacContainerBuilderTests_TypesRegistrableAsSelf_NewAPI()
        {
            //Arrange
            var autofacContainerBuilder = new AutofacContainerBuilder();

            //Act
            autofacContainerBuilder.For(typeof(Foo));
            var dependencyResolver = autofacContainerBuilder.Build();

            //Assert
            Assert.IsNotNull(dependencyResolver.Resolve <Foo>());
        }
        public void AutofacContainerBuilderTests_TypesRegistrableUsingImplementation()
        {
            //Arrange
            var autofacContainerBuilder = new AutofacContainerBuilder();

            //Act
            autofacContainerBuilder.ForInstanceOfType(new Foo())
            .KnownAs(typeof(IFoo));
            var dependencyResolver = autofacContainerBuilder.Build();

            //Assert
            Assert.IsNotNull(dependencyResolver.Resolve <IFoo>());
        }
        public void DependencyRegistrarExtensions_KnwonAsSelf_RegistersTypeAsItself()
        {
            //Arrange
            var builder = new AutofacContainerBuilder();

            //Act
            builder.For(typeof(Foo))
            .KnownAsSelf();
            var resolver = builder.Build();

            //Assert
            Assert.IsNotNull(resolver.Resolve <Foo>());
        }
        public void AutofacContainerBuilderTests_TypesRegistrableAsInterfaces()
        {
            //Arrange
            var autofacContainerBuilder = new AutofacContainerBuilder();

            //Act
            autofacContainerBuilder.For <Foo>()
            .KnownAs <IFoo>();
            var dependencyResolver = autofacContainerBuilder.Build();

            //Assert
            Assert.IsNotNull(dependencyResolver.Resolve <IFoo>());
        }
        public void AutofacContainerBuilderTests_NamedRegistration_ResolvableByName()
        {
            //Arrange
            var builder = new AutofacContainerBuilder();

            //Act
            builder.ForInstanceOfType(new Foo())
            .Named <Foo>("name")
            ;
            var resolver = builder.Build();

            //Assert
            Assert.IsNotNull(resolver.Resolve <Foo>("name"));
        }
        public void TestSendEmailTask()
        {
            var containerBuilder = new AutofacContainerBuilder();
            var bootstrapper     = new ProviderBootstrapper(containerBuilder, MockBuilder.BuildConfiguration());
            var methodResult     = bootstrapper.Load(new MockHosting());

            var container = containerBuilder.Build();

            bootstrapper.InitializeFramework(container);
            var sendEmailTask = container.Resolve <SendEmailTask>();
            var result        = sendEmailTask.Execute().Result;

            Assert.AreEqual(result.MethodResultState, MethodResultStates.Successful);
        }
Пример #18
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var builder = new AutofacContainerBuilder();
            var providerConfiguration = Configuration.GetSection("Vedaantees").Get <ProviderConfiguration>();
            var bootstrapper          = new ProviderBootstrapper(builder, providerConfiguration);

            bootstrapper.Load(_env);


            builder.Builder.Populate(services);
            ApplicationContainer = builder.Build();
            bootstrapper.InitializeFramework(ApplicationContainer);
            return(new AutofacServiceProvider(ApplicationContainer));
        }
Пример #19
0
        private void IocConfiguration()
        {
            var builder = new AutofacContainerBuilder(null).Get();

            builder.RegisterControllers(typeof(ReplaysController).Assembly);

            RegisterSecurity(builder);

            var container = builder.Build();

            System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            /*var dbService = container.Resolve<IDatabaseService>();
             * dbService.DropCreateAndInit(null);*/
        }
        public void AutofacContainerBuilder_ForFactoryTests_ForFactory_DelegateCanSetProperties()
        {
            //Arrange
            var autofacContainerBuilder = new AutofacContainerBuilder();

            //Act
            autofacContainerBuilder.ForFactory(x => new Foo()
            {
                Bar = new Bar()
            });
            var resolver = autofacContainerBuilder.Build();

            //Assert
            Assert.IsNotNull(resolver.Resolve <Foo>().Bar);
        }
        public void AutofacContainerBuilderTests_NamedRegistration_InvalidNameFailsResolution()
        {
            //Arrange
            var builder = new AutofacContainerBuilder();

            //Act
            builder.ForInstanceOfType(new Foo())
            .Named <Foo>("name");
            var resolver = builder.Build();

            //Assert
            var foo = resolver.TryResolve <Foo>("invalid");

            Assert.IsNotNull(foo);
            Assert.IsFalse(foo.Success);
        }
Пример #22
0
        public void AutofacContainerBuilder_WithTests_ProvidedMetaData_MappedToInstance()
        {
            //Arrange
            var builder = new AutofacContainerBuilder();

            //Act
            builder.For <Foo>()
            .WithMetadata <Metadata, string>(am => am.Value, "test");

            var resolver = builder.Build();

            //Assert
            var lazyFoo = resolver.Resolve <Lazy <Foo, Metadata> >();

            Assert.IsNotNull(lazyFoo);
            Assert.AreEqual("test", lazyFoo.Metadata.Value);
        }
Пример #23
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var builder = new AutofacContainerBuilder();
            var providerConfiguration = Configuration.GetSection("Vedaantees").Get <ProviderConfiguration>();
            var bootstrapper          = new ProviderBootstrapper(builder, providerConfiguration);

            bootstrapper.Load(_env);

            services.AddMvc();
            services.AddHangfire(x => x.UsePostgreSqlStorage(providerConfiguration.SqlStore.ConnectionString));

            builder.RegisterInstance <IConfiguration>(Configuration);
            builder.Builder.Populate(services);
            ApplicationContainer = builder.Build();
            bootstrapper.InitializeFramework(ApplicationContainer);

            return(new AutofacServiceProvider(ApplicationContainer));
        }
Пример #24
0
        static void Main()
        {
            var containerBuilder = new AutofacContainerBuilder();
            var container        = containerBuilder.Build();

            logger = container.Resolve <ILogger>();

            logger.Information("Dependencies built");

            MigrateDatabase(container.Resolve <BotContext>());

            SetupHangfire(container);
            SetupTelegram(container);

            logger.Warning("Service started and ready");

            Thread.Sleep(Timeout.Infinite);
        }
Пример #25
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var builder = new AutofacContainerBuilder();
            var providerConfiguration = Configuration.GetSection("Vedaantees").Get <ProviderConfiguration>();
            var bootstrapper          = new ProviderBootstrapper(builder, providerConfiguration);

            bootstrapper.Load(_env);
            LoadApiClientRegistrations(builder, bootstrapper.GetAssemblies);

            services.AddMvcCore(config => {
                //Enable this for security.
                //var policy = new AuthorizationPolicyBuilder()
                //                .RequireAuthenticatedUser()
                //                .Build();
                //config.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddAuthorization()
            .AddJsonFormatters();

            services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = providerConfiguration.SingleSignOnServer;
                options.RequireHttpsMetadata = false;
                options.ApiName   = "axelius-api";
                options.ApiSecret = "guess-thi$-not-di55icult-resource";
            });

            services.AddCors(options =>
            {
                options.AddPolicy("default", policy =>
                {
                    policy.WithOrigins(string.Join(',', Configuration.GetSection("Clients").Get <List <string> >()))
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            builder.RegisterInstance(Configuration);
            builder.Builder.Populate(services);
            ApplicationContainer = builder.Build();
            bootstrapper.InitializeFramework(ApplicationContainer);
            return(new AutofacServiceProvider(ApplicationContainer));
        }
Пример #26
0
        public void RebelAreaRegistrationReceivesMetadataFromIoC()
        {
            var codeBase     = Assembly.GetExecutingAssembly().CodeBase;
            var uri          = new Uri(codeBase);
            var path         = uri.LocalPath;
            var binFolder    = Path.GetDirectoryName(path);
            var settingsFile = new FileInfo(Path.Combine(binFolder, "web.config"));

            var autofacBuilder = new AutofacContainerBuilder();

            autofacBuilder.ForFactory(
                context => new RebelSettings(settingsFile))
            .KnownAsSelf();

            autofacBuilder.For <RebelAreaRegistration>()
            .KnownAsSelf()
            .WithResolvedParam(context => context.Resolve <IRouteHandler>("TreeRouteHandler"));

            //why is this here?

            var typeFinder         = new TypeFinder();
            var componentRegistrar = new RebelComponentRegistrar();

            componentRegistrar.RegisterEditorControllers(autofacBuilder, typeFinder);
            componentRegistrar.RegisterMenuItems(autofacBuilder, typeFinder);
            //componentRegistrar.RegisterPackageActions(autofacBuilder, typeFinder);
            componentRegistrar.RegisterPropertyEditors(autofacBuilder, typeFinder);
            componentRegistrar.RegisterSurfaceControllers(autofacBuilder, typeFinder);
            componentRegistrar.RegisterTreeControllers(autofacBuilder, typeFinder);

            //build the container
            var container = autofacBuilder.Build();

            var result = container.Resolve <RebelAreaRegistration>();

            Assert.IsNotNull(result);
        }
        public void UmbracoAreaRegistrationReceivesMetadataFromIoC()
        {
            var codeBase = Assembly.GetExecutingAssembly().CodeBase;
            var uri = new Uri(codeBase);
            var path = uri.LocalPath;
            var binFolder = Path.GetDirectoryName(path);
            var settingsFile = new FileInfo(Path.Combine(binFolder, "web.config"));

            var autofacBuilder = new AutofacContainerBuilder();

            autofacBuilder.ForFactory(
                context => new UmbracoSettings(settingsFile))
                .KnownAsSelf();

            autofacBuilder.For<UmbracoAreaRegistration>()
                .KnownAsSelf()
                .WithResolvedParam(context => context.Resolve<IRouteHandler>("TreeRouteHandler"));

            //why is this here? 

            var typeFinder = new TypeFinder();
            var componentRegistrar = new UmbracoComponentRegistrar();
            componentRegistrar.RegisterEditorControllers(autofacBuilder, typeFinder);
            componentRegistrar.RegisterMenuItems(autofacBuilder, typeFinder);
            //componentRegistrar.RegisterPackageActions(autofacBuilder, typeFinder);
            componentRegistrar.RegisterPropertyEditors(autofacBuilder, typeFinder);
            componentRegistrar.RegisterSurfaceControllers(autofacBuilder, typeFinder);
            componentRegistrar.RegisterTreeControllers(autofacBuilder, typeFinder);

            //build the container
            var container = autofacBuilder.Build();

            var result = container.Resolve<UmbracoAreaRegistration>();

            Assert.IsNotNull(result);
        }
        public void InitializeCompletely()
        {
            var containerBuilder = new AutofacContainerBuilder();
            var bootstrapper     = new ProviderBootstrapper(containerBuilder, MockBuilder.BuildConfiguration());
            var methodResult     = bootstrapper.Load(new MockHosting());

            var container = containerBuilder.Build();

            bootstrapper.InitializeFramework(container);

            Assert.AreEqual(methodResult.MethodResultState, MethodResultStates.Successful);
            Assert.AreNotEqual(container.Resolve <ILogger>(), null);
            Assert.AreNotEqual(container.Resolve <IDocumentStore>(), null);
            Assert.AreNotEqual(container.Resolve <IGraphStore>(), null);
            Assert.AreNotEqual(container.Resolve <ISqlStore>(), null);
            Assert.AreNotEqual(container.Resolve <IGenerateKey>(), null);
            Assert.AreNotEqual(container.Resolve <IHashKeys>(), null);
            Assert.AreNotEqual(container.Resolve <IEmailProvider>(), null);
            Assert.AreNotEqual(container.Resolve <ITemplateBuilder>(), null);
            Assert.AreNotEqual(container.Resolve <IBus>(), null);
            Assert.AreNotEqual(container.Resolve <ICommandService>(), null);
            Assert.AreNotEqual(container.Resolve <IEventBus>(), null);
            Assert.AreNotEqual(container.Resolve <IQueryService>(), null);
        }
Пример #29
0
        private static void Main(string[] args)
        {
            var binarySerializer = new DefaultBinarySerializer();

            var hostName = "127.0.0.1";
            var port = 5672;
            var userName = "******";
            var password = "******";
            var virtualName = "/";

            var endPoint = new RemoteEndpoint(hostName, virtualName, userName, password, port);

            var exChangeName = typeof(CreateUserCommand).Assembly.GetName().Name;

            var routingKey = MessageUtils.CurrentResponseRoutingKey;

            var responseRoutingKey = MessageUtils.CurrentResponseRoutingKey;

            var consumerContext = new ConsumerContext(exChangeName, responseRoutingKey, responseRoutingKey, routingKey, true);

            var channelPools = new CommunicateChannelFactoryPool(endPoint);

            var consumer = new PushMessageConsumer(channelPools, binarySerializer, consumerContext, new MessageResponseHandler());

            consumer.Start();

            var containerBuilder = new AutofacContainerBuilder();

            containerBuilder.RegisterInstance(channelPools);
            containerBuilder.RegisterInterface<IBinarySerializer, DefaultBinarySerializer>();

            DependencyResolver.SetResolver(new DefaultDependencyResolver(containerBuilder.Build()));

            var requestChannelPools = new RequestChannelPools();

            var commandTopicProvider = new UserTopicProvider();

            var commandService = new CommandService(requestChannelPools, commandTopicProvider);

            Console.WriteLine("begin to receive the result message");

            Stopwatch watch = new Stopwatch();
            watch.Start();

            for (var i = 0; i < 10000; i++)
            {
                var command = new CreateUserCommand(
                 "天涯狼" + DateTime.Now.ToString("yyyyMMddHHmmsss"),
                 DateTime.Now.ToString("yyyyMMddHHmmsss"),
                 true,
                 22);

                var commandResult = commandService.Send(command, 20);

                Console.WriteLine("message:{0} and number is {1}", commandResult.Message, i);
            }

            watch.Stop();

            Console.WriteLine("message:{0} ", watch.ElapsedMilliseconds);
            Console.ReadLine();
        }
Пример #30
0
        private static void Main(string[] args)
        {
            var containerBuilder = new AutofacContainerBuilder();

            var binarySerializer = new DefaultBinarySerializer();

            var eventHandleInitializer = new EventHandleProvider();
            eventHandleInitializer.Initialize(Assembly.GetExecutingAssembly(), Assembly.Load("Seven.Tests"));

            var commandInitializer = new CommandHandleProvider();
            commandInitializer.Initialize(Assembly.Load("Seven.Tests"));

            var messageTypeProvider = new MessageTypeProvider();
            messageTypeProvider.Initialize(Assembly.GetExecutingAssembly(), Assembly.Load("Seven.Tests"));

            containerBuilder.RegisterInstance(eventHandleInitializer);
            containerBuilder.RegisterInstance(commandInitializer);
            containerBuilder.RegisterInstance(messageTypeProvider);

            var mysqlEventStore = new MySqlEventStore(_mysqlConnection);

            var snapshotStorage = new MysqlSnapshotStorage(_mysqlConnection);

            var aggregateRootStorage = new MysqlAggregateRootStorage(_mysqlConnection);

            var aggregateRootMemory = new AggregateRootMemoryCache();

            var nonEventSouringRepository = new NonEventSouringRepository(aggregateRootStorage, binarySerializer);

            var eventSouringRepository = new EventSouringRepository(mysqlEventStore, snapshotStorage, binarySerializer,
                aggregateRootMemory);

            var endPoint = new RemoteEndpoint("127.0.0.1", "/", "guest", "guest", 5672);

            var exChangeName = typeof(CreateUserCommand).Assembly.GetName().Name; ;

            var responseRoutingKey = MessageUtils.CurrentResponseRoutingKey;

            var channelPools = new CommunicateChannelFactoryPool(endPoint);

            containerBuilder.RegisterInstance(channelPools);
            containerBuilder.RegisterInterface<IBinarySerializer, DefaultBinarySerializer>();

            DependencyResolver.SetResolver(new DefaultDependencyResolver(containerBuilder.Build()));

            var requestChannelPools = new RequestChannelPools();

            var commandTopicProvider = new UserTopicProvider();

            var eventTopicProvider = new UserEEventTopicProvider();

            var eventPublisher = new EventPublisher(requestChannelPools, eventTopicProvider);

            var commandProssor = new DefaultCommandProssor(mysqlEventStore, eventSouringRepository, commandInitializer, eventPublisher, snapshotStorage, binarySerializer);

            var messageHandler = new MessageRequestHandler(commandProssor);

            for (var i = 0; i < 5; i++)
            {
                var routingKey = string.Format("{0}_{1}_{2}", exChangeName, "command", i);

                var consumerContext = new ConsumerContext(exChangeName, routingKey, routingKey, responseRoutingKey, false, true);

                var consumer = new PushMessageConsumer(channelPools, binarySerializer, consumerContext, messageHandler);

                consumer.Start();

                Console.WriteLine("Started.");
            }

            for (var i = 0; i < 5; i++)
            {
                var routingKey = string.Format("{0}_{1}_{2}", exChangeName, "event", i);

                var consumerContext = new ConsumerContext(exChangeName, routingKey, routingKey, responseRoutingKey, false, true);

                var consumer = new PushMessageConsumer(channelPools, binarySerializer, consumerContext, messageHandler);

                consumer.Start();

                Console.WriteLine("Started.");
            }

            Console.WriteLine("begin to consumer the message.");

            Console.ReadLine();
        }