Example #1
0
        public void GetAllVendorDetails_Test()
        {
            using (var lifetimeScope = AutofacResolver.GetLifeTimeScope(_environment))
            {
                //Retreive service from scope
                var vendorController = lifetimeScope.Resolve <VendorController>();
                vendorController.Request = new HttpRequestMessage();
                vendorController.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());

                var result = vendorController.Get().Result;

                // Assertions
                var    actualResponse = result as ResponseMessageResult;
                object responseContent;
                Assert.IsTrue(result != null);
                Assert.AreEqual(HttpStatusCode.OK, actualResponse.Response.StatusCode);
                Assert.IsTrue(actualResponse.Response.TryGetContentValue(out responseContent));
                var jsonObject = JObject.FromObject(responseContent);
                var errors     = jsonObject.Property("Errors").Value.ToObject <List <string> >();
                var vendors    = jsonObject.Property("Vendors").Value.ToObject <List <Vendor> >();
                Assert.IsTrue(errors.Count == 0);
                Assert.IsNotNull(actualResponse);
                Assert.IsNotNull(vendors);
                Assert.AreEqual(1, vendors.Count, "The number Vendors returned should be 3");
                Assert.IsTrue(vendors[0].Projects[0].Code == "PP123456", "Invalid Project Code");
                Assert.AreEqual(vendors.First().Id, 1,
                                "Wrong Id");
                _mockDbContext.Received(1);
            }
        }
Example #2
0
        public static void Initialize()
        {
            var builder = new ContainerBuilder();

            // Views
            var appAssembly = typeof(App).GetTypeInfo().Assembly;

            builder.RegisterAssemblyTypes(appAssembly)
            .Where(x => x.Name.EndsWith("View", StringComparison.Ordinal));

            // ViewModels
            var coreAssembly = Assembly.Load(new AssemblyName("TinyMvvmSample.Core"));

            builder.RegisterAssemblyTypes(coreAssembly)
            .Where(x => x.Name.EndsWith("ViewModel", StringComparison.Ordinal));

            // Navigation
            var navigationHelper = new TinyNavigationHelper.Forms.FormsNavigationHelper(Application.Current);

            navigationHelper.RegisterViewsInAssembly(appAssembly);
            builder.RegisterInstance <INavigationHelper>(navigationHelper);

            builder.RegisterType <NewsService>().As <INewsService>();

            var container = builder.Build();

            var autofacResolver = new AutofacResolver(container);

            Resolver.SetResolver(autofacResolver);

            TinyMvvm.Forms.TinyMvvm.Initialize();

            navigationHelper.SetRootView("MainView");
        }
        public void TestDependencyInjectionThrowsWhenMissing()
        {
            var container = new ContainerBuilder();
            var resolver = new AutofacResolver(container.Build());

            resolver.Resolve<IFoo>();
        }
Example #4
0
        public static void Initialize()
        {
            var builder = new ContainerBuilder();

            var asm = typeof(App).GetTypeInfo().Assembly;

            builder.RegisterAssemblyTypes(asm).Where(x => x.Name.EndsWith("View", StringComparison.Ordinal));

            var coreAssembly = Assembly.Load("Appitecture.Core");

            builder.RegisterAssemblyTypes(coreAssembly).Where(x => x.Name.EndsWith("ViewModel", StringComparison.Ordinal));

            var navigationHelper = new TinyNavigationHelper.Forms.FormsNavigationHelper(Application.Current);

            navigationHelper.RegisterViewsInAssembly(asm);
            builder.RegisterInstance <INavigationHelper>(navigationHelper);
            builder.RegisterType <GetLoginRequests>();

            builder.RegisterType <GetAssistantRequest>();
            builder.RegisterType <GetAssistantsRequest>();
            builder.RegisterType <GetBookAssistantsRequest>();
            builder.RegisterType <GetHistoryAssistantsRequest>();
            var container = builder.Build();
            var resolver  = new AutofacResolver(container);

            Resolver.SetResolver(resolver);

            TinyMvvm.Forms.TinyMvvm.Initialize();
            //    navigationHelper.SetRootView("AssistantMapView");
            navigationHelper.SetRootView("LoginView");
        }
        public static void Initialize(App app)
        {
            if (!hasRunEarlyInit)
            {
                EarlyInitialize();
            }

            // Navigation
            var navigationHelper = new TinyNavigationHelper.Forms.FormsNavigationHelper(app);

            navigationHelper.RegisterViewsInAssembly(mainAsm);
            builder.RegisterInstance <INavigationHelper>(navigationHelper);

            // Platform specifics
            Platform?.Initialize(app, builder);

            // Build and set
            var container = builder.Build();
            var resolver  = new AutofacResolver(container);

            Resolver.SetResolver(resolver);

            // Init TinyMvvm
            TinyMvvm.Forms.TinyMvvm.Initialize();

            // Init TinyPubSub
            TinyPubSubLib.TinyPubSubForms.Init(app);

            // Init TinyCache
            var cacheFirstPolicy = new TinyCachePolicy().SetMode(TinyCacheModeEnum.CacheFirst).SetFetchTimeout(Settings.Current.FetchTimeout);

            TinyCache.SetCacheStore(new XamarinPropertyStorage());
            TinyCache.SetBasePolicy(cacheFirstPolicy);
        }
Example #6
0
        private static void ConfigAutofac(HttpConfiguration config)
        {
            var configurationBuilder = new ConfigurationBuilder()
                                       .SetBasePath(HttpRuntime.AppDomainAppPath)
                                       .AddJsonFile("appSettings.json", false, true);

            var root = configurationBuilder.Build();

            var builder = new ContainerBuilder();

            builder.RegisterOptions();

            RegisterConfig(builder, root);
            var binder = new AutofacBinder(builder);

            binder.Register <MapBuild, CacheBuild, UmbracoQueryFactory, UmbracoFetcher>();

            builder.RegisterApiControllers(typeof(WebApiApplication).Assembly);
            builder.RegisterModule <AutofacWebTypesModule>();

            var container = builder.Build();
            var resolver  = new AutofacWebApiDependencyResolver(container);

            config.DependencyResolver = resolver;

            var umbResolver = new AutofacResolver(container);

            binder.Setup(umbResolver);
        }
        public void TestDependencyInjectionCanBeMissing()
        {
            var container = new ContainerBuilder();
            var resolver = new AutofacResolver(container.Build());

            IFoo value;
            Assert.That(resolver.TryResolve(out value), Is.False);
        }
Example #8
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     DependencyResolver.SetResolver(new AutofacDependencyResolver(AutofacResolver.GetContainer()));
 }
Example #9
0
        public void Autofac_Resolve_Success()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<Math>().As<IMath>();
            var container = builder.Build();

            var slowpoke = new AutofacResolver();
            slowpoke.Resolve(typeof(IMath), container);
        }
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     GlobalConfiguration.Configure(WebApiConfig.Register);
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     AutofacResolver.ResolveDependies();
 }
        public void TestDependencyInjectionSucceeds()
        {
            var container = new ContainerBuilder();
            var builder = new DemandA();
            builder.Build(container);

            var resolver = new AutofacResolver(container.Build());

            Assert.That(resolver.Resolve<IFoo>(), Is.InstanceOf<A>());
        }
        public void AutofacResolver_DoesNot_Resolve_NonRegistered_ContactRepository_Test()
        {
            var builder = new ContainerBuilder();
            var container = builder.Build();

            var resolver = new AutofacResolver(container);
            var instance = resolver.GetService(typeof(IContactRepository));

            Assert.IsNull(instance);
        }
Example #13
0
        public void AutofacResolver_DoesNot_Resolve_NonRegistered_ContactRepository_Test()
        {
            var builder   = new ContainerBuilder();
            var container = builder.Build();

            var resolver = new AutofacResolver(container);
            var instance = resolver.GetService(typeof(IContactRepository));

            Assert.IsNull(instance);
        }
 public AutofacMvcResolver(IDependencyResolver resolver)
     : base(resolver)
 {
     _dependencyResolver = resolver as AutofacResolver;
     if (_dependencyResolver == null)
     {
         throw new ArgumentException("Must be of type 'Rebel.Framework.DependencyManagement.Autofac.AutofacResolver'", "resolver");
     }
     _realDependencyResolver = new AutofacDependencyResolver(_dependencyResolver.AutofacContainer);
 }
Example #15
0
        public void Autofac_Resolve_Success()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType <Math>().As <IMath>();
            var container = builder.Build();

            var slowpoke = new AutofacResolver();

            slowpoke.Resolve(typeof(IMath), container);
        }
        public void AutofacResolver_Resolves_Registered_ContactRepository_Test()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<InMemoryContactRepository>().As<IContactRepository>();
            var container = builder.Build();

            var resolver = new AutofacResolver(container);
            var instance = resolver.GetService(typeof(IContactRepository));

            Assert.IsNotNull(instance);
        }
Example #17
0
        public virtual void SetUp()
        {
            var configurationBuilder = new Autofac.ContainerBuilder();

            var fresh = new CreateFreshDatabase();
            fresh.Create(configurationBuilder);

            var resolver = new AutofacResolver(configurationBuilder);

            Database = resolver.Resolve<IDocumentStore>();
            Universe = new MockUniverse();
        }
Example #18
0
        public void AutofacResolver_Resolves_Registered_ContactRepository_Test()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType <InMemoryContactRepository>().As <IContactRepository>();
            var container = builder.Build();

            var resolver = new AutofacResolver(container);
            var instance = resolver.GetService(typeof(IContactRepository));

            Assert.IsNotNull(instance);
        }
Example #19
0
        public App(object platform)
        {
            InitializeComponent();

            var resolver = new AutofacResolver();

            resolver.ScanAssembly <CategoryService>();   // Marketplacxe.Client
            resolver.ScanAssembly <NavigationService>(); // Prolix.Xam
            resolver.ScanAssembly <RestService>();       // Prolix.Client

            var forms = new FormsManager(this, resolver);

            // Init the application and the Main page
            forms.Run <LoginViewModel>();
        }
Example #20
0
        public void Initialize()
        {
            var resolver = new AutofacResolver();

            // Map all assemblies
            resolver.ScanAssembly <CategoryService>(); // Services
            resolver.ScanAssembly <SecurityContext>(); // Domain

            // Mocking the data context
            resolver.ScanAssembly <MockDataContext>(); // Mock: Data

            // Builds the IoC container
            resolver.Build();

            this._resolver = resolver;
        }
Example #21
0
        public void AutofacResolver_Resolves_Registered_Both_Instaces_Of_IContactRepository()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType <InMemoryContactRepository>().As <IContactRepository>();
            builder.RegisterType <FileContactRepository>().As <IContactRepository>();
            var container = builder.Build();

            var config   = new HttpConfiguration();
            var resolver = new AutofacResolver(container);

            config.DependencyResolver = resolver;
            var repositories = config.DependencyResolver.GetServices(typeof(IContactRepository));

            repositories.Count().ShouldEqual(2);
        }
Example #22
0
        static void ConfigureDependencies(HttpConfiguration config)
        {
            // IoC container
            var resolver = new AutofacResolver();

            // Map app dependencies
            resolver.ScanAssembly <SecurityContext>();     // Domain
            resolver.ScanAssembly <DataContext>();         // Data
            resolver.ScanAssembly <CategoryService>();     // Logic
            resolver.ScanAssembly <PermissionAttribute>(); // Api

            // Map code dependencies
            resolver.ScanAssembly <GlobalAuthorizeAttribute>(); // Filters
            resolver.ScanAssembly <IdentityManager>();          // Identity

            // Map all controllers
            resolver.ScanTypes <IHttpController>(Assembly.GetExecutingAssembly());

            // Setting the Resolver
            config.DependencyResolver = resolver.GetHttpResolver();
        }
Example #23
0
 public void Setup()
 {
     AutofacResolver.Init();
 }
Example #24
0
 public void TestClassService()
 {
     var classService = AutofacResolver.Resolve <IClassService>();
     var result       = classService.GetClassesResponse().ToList();
 }
        public void AutofacResolver_Resolves_Registered_Both_Instaces_Of_IContactRepository()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<InMemoryContactRepository>().As<IContactRepository>();
            builder.RegisterType<FileContactRepository>().As<IContactRepository>();
            var container = builder.Build();

            var config = new HttpConfiguration();
            var resolver = new AutofacResolver(container);

            config.DependencyResolver = resolver;
            var repositories = config.DependencyResolver.GetServices(typeof(IContactRepository));

            repositories.Count().ShouldEqual(2);
        }
        /// <summary>
        /// Extension method to configure IdentityServer in the hosting application.
        /// </summary>
        /// <param name="app">The application.</param>
        /// <param name="options">The <see cref="IdentityServer3.Core.Configuration.IdentityServerOptions"/>.</param>
        /// <param name="autofacResolver">The AutofacResolver.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">
        /// app
        /// or
        /// options
        /// </exception>
        public static IAppBuilder UseIdentityServer(this IAppBuilder app, IdentityServerOptions options, out AutofacResolver autofacResolver)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            options.Validate();

            if (options.RequireSsl)
            {
                app.Use <RequireSslMiddleware>();
            }

            if (options.LoggingOptions.EnableKatanaLogging)
            {
                app.SetLoggerFactory(new LibLogKatanaLoggerFactory());
            }

            if (options.LoggingOptions.ShowPII)
            {
                Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
            }

            app.UseEmbeddedFileServer();

            app.ConfigureRequestId();
            app.ConfigureDataProtectionProvider(options);
            app.ConfigureIdentityServerBaseUrl(options.PublicOrigin);

            app.ConfigureRequestBodyBuffer();

            // this needs to be earlier than the autofac middleware so anything is disposed and re-initialized
            // if we send the request back into the pipeline to render the logged out page
            app.ConfigureRenderLoggedOutPage();

            var container = AutofacConfig.Configure(options);

            app.UseAutofacMiddleware(container);

            app.UseCors();
            app.ConfigureCookieAuthentication(options.AuthenticationOptions.CookieOptions, options.DataProtector);

            // this needs to be before external middleware
            app.ConfigureSignOutMessageCookie();


            if (options.PluginConfiguration != null)
            {
                options.PluginConfiguration(app, options);
            }

            if (options.AuthenticationOptions.IdentityProviders != null)
            {
                options.AuthenticationOptions.IdentityProviders(app, Constants.ExternalAuthenticationType);
            }

            app.ConfigureHttpLogging(options.LoggingOptions);

            SignatureConversions.AddConversions(app);

            var httpConfig = WebApiConfig.Configure(options, container);

            app.UseAutofacWebApi(httpConfig);
            app.UseWebApi(httpConfig);

            using (var child = container.CreateScopeWithEmptyOwinContext())
            {
                var eventSvc = child.Resolve <IEventService>();
                // TODO -- perhaps use AsyncHelper instead?
                DoStartupDiagnosticsAsync(options, eventSvc).Wait();
            }

            autofacResolver = new AutofacResolver(container);

            return(app);
        }
 public AutofacAggregateRootFactory(IResolver resolver)
 {
     _resolver = (AutofacResolver)resolver;
 }
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            builder.RegisterModule(new FiberModule <DialogTask>());

            // singleton components

            builder
            .Register(c => new ResourceManager("Microsoft.Bot.Builder.Resource.Resources", typeof(Resource.Resources).Assembly))
            .As <ResourceManager>()
            .SingleInstance();

            // every lifetime scope is driven by a message

            builder
            .Register((c, p) => p.TypedAs <IMessageActivity>())
            .AsSelf()
            .AsImplementedInterfaces()
            .InstancePerMatchingLifetimeScope(LifetimeScopeTag);

            // make the address and cookie available for the lifetime scope

            builder
            .Register(c => Address.FromActivity(c.Resolve <IActivity>()))
            .AsImplementedInterfaces()
            .InstancePerMatchingLifetimeScope(LifetimeScopeTag);

#pragma warning disable CS0618
            builder
            .RegisterType <ResumptionCookie>()
            .AsSelf()
            .InstancePerMatchingLifetimeScope(LifetimeScopeTag);
#pragma warning restore CS0618

            builder
            .Register(c => c.Resolve <IActivity>().ToConversationReference())
            .AsSelf()
            .InstancePerMatchingLifetimeScope(LifetimeScopeTag);

            // components not marked as [Serializable]
            builder
            .RegisterType <MicrosoftAppCredentials>()
            .AsSelf()
            .SingleInstance();

            builder
            // not resolving IEqualityComparer<IAddress> from container because it's a very local policy
            // and yet too broad of an interface.  could explore using tags for registration overrides.
            .Register(c => new LocalMutualExclusion <IAddress>(new ConversationAddressComparer()))
            .As <IScope <IAddress> >()
            .SingleInstance();

            builder
            .Register(c => new ConnectorClientFactory(c.Resolve <IAddress>(), c.Resolve <MicrosoftAppCredentials>()))
            .As <IConnectorClientFactory>()
            .ExternallyOwned();

            builder
            .Register(c => c.Resolve <IConnectorClientFactory>().MakeConnectorClient())
            .As <IConnectorClient>()
            .ExternallyOwned();

            builder
            .Register(c => c.Resolve <IConnectorClientFactory>().MakeStateClient())
            .As <IStateClient>()
            .ExternallyOwned();

            builder
            .RegisterType <ChannelCapability>()
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <ConnectorStore, IBotDataStore <BotData> >()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <InMemoryDataStore, IBotDataStore <BotData> >()
            .SingleInstance();

            builder
            .RegisterKeyedType <CachingBotDataStore, IBotDataStore <BotData> >()
            .WithParameter((pi, c) => pi.ParameterType == typeof(CachingBotDataStoreConsistencyPolicy),
                           (pi, c) => CachingBotDataStoreConsistencyPolicy.ETagBasedConsistency)
            .InstancePerLifetimeScope();

            builder
            .RegisterAdapterChain <IBotDataStore <BotData> >
            (
                typeof(ConnectorStore),
                typeof(CachingBotDataStore)
            )
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <JObjectBotData, IBotData>()
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <DialogTaskManagerBotDataLoader, IBotData>()
            .InstancePerLifetimeScope();

            builder
            .RegisterAdapterChain <IBotData>
            (
                typeof(JObjectBotData),
                typeof(DialogTaskManagerBotDataLoader)
            )
            .InstancePerLifetimeScope();

            builder
            .Register((c, p) => new BotDataBagStream(p.TypedAs <IBotDataBag>(), p.TypedAs <string>()))
            .As <Stream>()
            .InstancePerDependency();

            builder
            .Register(c => new DialogTaskManager(DialogModule.BlobKey,
                                                 c.Resolve <JObjectBotData>(),
                                                 c.Resolve <IStackStoreFactory <DialogTask> >(),
                                                 c.Resolve <Func <IDialogStack, CancellationToken, IDialogContext> >(),
                                                 c.Resolve <IEventProducer <IActivity> >()))
            .AsSelf()
            .As <IDialogTaskManager>()
            .As <IDialogTasks>()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <DialogSystem>()
            .As <IDialogSystem>();

            builder
            .RegisterType <DialogContext>()
            .As <IDialogContext>()
            .InstancePerDependency();

            builder
            .Register(c =>
            {
                var cc = c.Resolve <IComponentContext>();

                Func <string, IBotDataBag, IStore <IFiberLoop <DialogTask> > > make = (taskId, botDataBag) =>
                {
                    var stream = cc.Resolve <Stream>(TypedParameter.From(botDataBag), TypedParameter.From(taskId));
                    return(cc.Resolve <IStore <IFiberLoop <DialogTask> > >(TypedParameter.From(stream)));
                };

                return(make);
            })
            .As <Func <string, IBotDataBag, IStore <IFiberLoop <DialogTask> > > >()
            .InstancePerDependency();


            builder.Register(c => c.Resolve <IDialogTaskManager>().DialogTasks[0])
            .As <IDialogStack>()
            .As <IDialogTask>()
            .InstancePerLifetimeScope();

            // Scorable implementing "/deleteprofile"
            builder
            .Register(c => new Regex("^(\\s)*/deleteprofile", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace))
            .Keyed <Regex>(Key_DeleteProfile_Regex)
            .SingleInstance();

            builder
            .Register(c => new DeleteProfileScorable(c.Resolve <IDialogStack>(), c.Resolve <IBotData>(), c.Resolve <IBotToUser>(), c.ResolveKeyed <Regex>(Key_DeleteProfile_Regex)))
            .As <IScorable <IActivity, double> >()
            .InstancePerLifetimeScope();

            // scorable implementing "end conversation"
            builder
            .RegisterInstance(EndConversationEvent.MakeScorable())
            .As <IScorable <IResolver, double> >()
            .SingleInstance();

            builder
            .Register(c =>
            {
                var cc = c.Resolve <IComponentContext>();
                Func <IActivity, IResolver> make = activity =>
                {
                    var resolver = NoneResolver.Instance;
                    resolver     = new EnumResolver(resolver);
                    resolver     = new AutofacResolver(cc, resolver);
                    resolver     = new ArrayResolver(resolver,
                                                     activity,
                                                     cc.Resolve <IBotToUser>(),
                                                     cc.Resolve <IBotData>(),
                                                     cc.Resolve <IDialogSystem>());
                    resolver = new ActivityResolver(resolver);
                    resolver = new EventActivityValueResolver(resolver);
                    resolver = new InvokeActivityValueResolver(resolver);
                    return(resolver);
                };
                return(make);
            })
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <DialogRouter>()
            .Keyed <IScorable <IActivity, double> >(Key_Dialog_Router)
            .InstancePerLifetimeScope();

            builder
            .RegisterType <EventQueue <IActivity> >()
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <ReactiveDialogTask>()
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .Register(c => new ScoringEventLoop <double>(c.Resolve <ReactiveDialogTask>(), c.Resolve <ReactiveDialogTask>(), c.Resolve <IEventConsumer <IActivity> >(), c.ResolveKeyed <IScorable <IActivity, double> >(Key_Dialog_Router)))
            .As <IEventLoop>()
            .InstancePerLifetimeScope();

            // register IDataBag that is used for to load/save ResumptionData
            builder
            .Register(c =>
            {
                var cc = c.Resolve <IComponentContext>();
                Func <IBotDataBag> make = () =>
                {
                    return(cc.Resolve <IBotData>().PrivateConversationData);
                };
                return(make);
            })
            .As <Func <IBotDataBag> >()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <ResumptionContext>()
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <LocaleFinder>()
            .AsSelf()
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

            // IPostToBot services

            builder
            .RegisterKeyedType <NullPostToBot, IPostToBot>()
            .SingleInstance();

            builder
            .RegisterKeyedType <PassPostToBot, IPostToBot>()
            .InstancePerDependency();

            builder
            .RegisterKeyedType <EventLoopDialogTask, IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <PersistentDialogTask, IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <ExceptionTranslationDialogTask, IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <SerializeByConversation, IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <SetAmbientThreadCulture, IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <PostUnhandledExceptionToUser, IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <LogPostToBot, IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <QueueDrainingDialogTask, IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterAdapterChain <IPostToBot>
            (
                typeof(EventLoopDialogTask),
                typeof(SetAmbientThreadCulture),
                typeof(QueueDrainingDialogTask),
                typeof(PersistentDialogTask),
                typeof(ExceptionTranslationDialogTask),
                typeof(SerializeByConversation),
                typeof(PostUnhandledExceptionToUser),
                typeof(LogPostToBot)
            )
            .InstancePerLifetimeScope();

            // other

            builder
            .RegisterType <NullActivityLogger>()
            .AsImplementedInterfaces()
            .SingleInstance();

            builder
            .RegisterType <KeyboardCardMapper>()
            .AsImplementedInterfaces()
            .SingleInstance();

            builder
            .RegisterType <SetLocalTimestampMapper>()
            .AsImplementedInterfaces()
            .SingleInstance();

            // IBotToUser services
            builder
            .RegisterType <InputHintQueue>()
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <NullBotToUser, IBotToUser>()
            .SingleInstance();

            builder
            .RegisterKeyedType <PassBotToUser, IBotToUser>()
            .InstancePerDependency();

            builder
            .RegisterKeyedType <AlwaysSendDirect_BotToUser, IBotToUser>()
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <AutoInputHint_BotToUser, IBotToUser>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <MapToChannelData_BotToUser, IBotToUser>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <LogBotToUser, IBotToUser>()
            .InstancePerLifetimeScope();

#pragma warning disable CS1587
            /// <see cref="LogBotToUser"/> is composed around <see cref="MapToChannelData_BotToUser"/> is composed around
            /// <see cref="AlwaysSendDirect_BotToUser"/>.  The complexity of registering each component is pushed to a separate
            /// registration method, and each of these components are replaceable without re-registering
            /// the entire adapter chain by registering a new component with the same component key.
#pragma warning restore CS1587
            builder
            .RegisterAdapterChain <IBotToUser>
            (
                typeof(AlwaysSendDirect_BotToUser),
                typeof(AutoInputHint_BotToUser),
                typeof(MapToChannelData_BotToUser),
                typeof(LogBotToUser)
            )
            .InstancePerLifetimeScope();
        }
Example #29
0
        public static void Initialize(App app)
        {
            var builder = new ContainerBuilder();

            // Views
            var ass = app.GetType().Assembly;

            builder.RegisterAssemblyTypes(ass)
            .Where(x => x.Name.EndsWith("View", StringComparison.Ordinal));

            // ViewModels
            builder.RegisterAssemblyTypes(ass)
            .Where(x => x.Name.EndsWith("ViewModel", StringComparison.Ordinal));

            builder.RegisterAssemblyTypes(typeof(Core.Services.ShoppingService).Assembly)
            .Where(x => x.Name.EndsWith("Service", StringComparison.Ordinal)).SingleInstance();

            // Navigation
            var navigationHelper = new TinyNavigationHelper.Forms.FormsNavigationHelper(app);

            navigationHelper.RegisterViewsInAssembly(ass);
            builder.RegisterInstance <INavigationHelper>(navigationHelper);

            // Setup translation backend https://github.com/TinyStuff/TinyTranslation for translation backend
            var translator = new TranslationHelper(new CustomTranslationClient());

            //var translator = new TranslationHelper(new System.Uri("http://tinytranslation.azurewebsites.net"), "f17528d1-0dd0-4181-90b8-0853c62178a9");

            ObjectEditor.Translate = (string arg) =>
            {
                Console.WriteLine("Translate from ObjectEditor");
                return(translator.Translate(arg));
            };

            // Register translator
            builder.Register <TranslationHelper>((a) =>
            {
                return(translator);
            }).SingleInstance();

            // Build and set
            var container = builder.Build();
            var resolver  = new AutofacResolver(container);

            Resolver.SetResolver(resolver);

            // Init cache and settings
            TinyCache.TinyCache.SetCacheStore(new XamarinPropertyStorage());
            var cacheFirstPolicy = new TinyCachePolicy().SetMode(TinyCacheModeEnum.FetchFirst).SetFetchTimeout(1600);

            TinyCache.TinyCache.SetBasePolicy(cacheFirstPolicy);

            //// Enable cache for translations
            //var oldMethod = translator.FetchLanguageMethod;
            //translator.FetchLanguageMethod = async (locale) => await TinyCache.TinyCache.RunAsync<TinyTranslation.TranslationDictionary>("trans-" + locale, async () =>
            //{
            //    return await oldMethod(locale);
            //}, new TinyCachePolicy() {
            //    Mode = TinyCacheModeEnum.CacheFirst
            //});

            // Set translator to markup extension
            ansExtension.Translator = translator;

            var lng = translator.CurrentLocale;

            translator.Init("sv");

            // Init TinyMvvm
            TinyMvvm.Forms.TinyMvvm.Initialize();

            var asm = typeof(App).GetTypeInfo().Assembly;

            navigationHelper.RegisterViewsInAssembly(asm);

            // Init TinyPubSub
            TinyPubSubLib.TinyPubSubForms.Init(app);

            // Platform specifics
            Platform?.Initialize(app, builder);
        }
Example #30
0
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            builder.RegisterModule(new FiberModule <DialogTask>());

            // singleton components

            builder
            .Register(c => new ResourceManager("Microsoft.Bot.Builder.Resource.Resources", typeof(Resource.Resources).Assembly))
            .As <ResourceManager>()
            .SingleInstance();

            // every lifetime scope is driven by a message

            builder
            .Register((c, p) => p.TypedAs <IMessageActivity>())
            .AsSelf()
            .AsImplementedInterfaces()
            .InstancePerMatchingLifetimeScope(LifetimeScopeTag);

            // make the address and cookie available for the lifetime scope

            builder
            .Register(c => Address.FromActivity(c.Resolve <IActivity>()))
            .AsImplementedInterfaces()
            .InstancePerMatchingLifetimeScope(LifetimeScopeTag);

            builder
            .RegisterType <ResumptionCookie>()
            .AsSelf()
            .InstancePerMatchingLifetimeScope(LifetimeScopeTag);

            // components not marked as [Serializable]
            builder
            .RegisterType <MicrosoftAppCredentials>()
            .AsSelf()
            .SingleInstance();

            builder
            // not resolving IEqualityComparer<IAddress> from container because it's a very local policy
            // and yet too broad of an interface.  could explore using tags for registration overrides.
            .Register(c => new LocalMutualExclusion <IAddress>(new ConversationAddressComparer()))
            .As <IScope <IAddress> >()
            .SingleInstance();

            builder
            .Register(c => new ConnectorClientFactory(c.Resolve <IAddress>(), c.Resolve <MicrosoftAppCredentials>()))
            .As <IConnectorClientFactory>()
            .InstancePerLifetimeScope();

            builder
            .Register(c => c.Resolve <IConnectorClientFactory>().MakeConnectorClient())
            .As <IConnectorClient>()
            .InstancePerLifetimeScope();

            builder
            .Register(c => c.Resolve <IConnectorClientFactory>().MakeStateClient())
            .As <IStateClient>()
            .InstancePerLifetimeScope();

            builder
            .Register(c => new DetectChannelCapability(c.Resolve <IAddress>()))
            .As <IDetectChannelCapability>()
            .InstancePerLifetimeScope();

            builder
            .Register(c => c.Resolve <IDetectChannelCapability>().Detect())
            .As <IChannelCapability>()
            .InstancePerLifetimeScope();

            builder.RegisterType <ConnectorStore>()
            .AsSelf()
            .InstancePerLifetimeScope();

            // If bot wants to use InMemoryDataStore instead of
            // ConnectorStore, the below registration should be used
            // as the inner IBotDataStore for CachingBotDataStore

            /*builder.RegisterType<InMemoryDataStore>()
             *  .AsSelf()
             *  .SingleInstance(); */

            builder.Register(c => new CachingBotDataStore(c.Resolve <ConnectorStore>(),
                                                          CachingBotDataStoreConsistencyPolicy.ETagBasedConsistency))
            .As <IBotDataStore <BotData> >()
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <JObjectBotData>()
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .Register(c => new DialogTaskManagerBotDataLoader(c.Resolve <JObjectBotData>(),
                                                              c.Resolve <IDialogTaskManager>()))
            .As <IBotData>()
            .InstancePerLifetimeScope();

            builder
            .Register((c, p) => new BotDataBagStream(p.TypedAs <IBotDataBag>(), p.TypedAs <string>()))
            .As <Stream>()
            .InstancePerDependency();

            builder
            .Register(c => new DialogTaskManager(DialogModule.BlobKey,
                                                 c.Resolve <JObjectBotData>(),
                                                 c.Resolve <IStackStoreFactory <DialogTask> >(),
                                                 c.Resolve <Func <IDialogStack, CancellationToken, IDialogContext> >()))
            .AsSelf()
            .As <IDialogTaskManager>()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <DialogContext>()
            .As <IDialogContext>()
            .InstancePerDependency();


            builder
            .Register(c =>
            {
                var cc = c.Resolve <IComponentContext>();

                Func <string, IBotDataBag, IStore <IFiberLoop <DialogTask> > > make = (taskId, botDataBag) =>
                {
                    var stream = cc.Resolve <Stream>(TypedParameter.From(botDataBag), TypedParameter.From(taskId));
                    return(cc.Resolve <IStore <IFiberLoop <DialogTask> > >(TypedParameter.From(stream)));
                };

                return(make);
            })
            .As <Func <string, IBotDataBag, IStore <IFiberLoop <DialogTask> > > >()
            .InstancePerDependency();


            builder.Register(c => c.Resolve <IDialogTaskManager>().DialogTasks[0])
            .As <IDialogStack>()
            .As <IDialogTask>()
            .InstancePerLifetimeScope();


            // Scorable implementing "/deleteprofile"
            builder
            .Register(c => new Regex("^(\\s)*/deleteprofile", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace))
            .Keyed <Regex>(Key_DeleteProfile_Regex)
            .SingleInstance();

            builder
            .Register(c => new DeleteProfileScorable(c.Resolve <IDialogStack>(), c.Resolve <IBotData>(), c.Resolve <IBotToUser>(), c.ResolveKeyed <Regex>(Key_DeleteProfile_Regex)))
            .As <IScorable <IActivity, double> >()
            .InstancePerLifetimeScope();

            builder
            .Register(c =>
            {
                var cc = c.Resolve <IComponentContext>();
                Func <IActivity, IResolver> make = activity =>
                {
                    var resolver = NoneResolver.Instance;
                    resolver     = new EnumResolver(resolver);
                    resolver     = new AutofacResolver(cc, resolver);
                    resolver     = new ArrayResolver(resolver,
                                                     activity,
                                                     cc.Resolve <IDialogStack>(),
                                                     cc.Resolve <IBotToUser>(),
                                                     cc.Resolve <IBotData>(),
                                                     cc.Resolve <IDialogTaskManager>());
                    resolver = new ActivityResolver(resolver);
                    return(resolver);
                };
                return(make);
            })
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <DialogRouter>()
            .Keyed <IScorable <IActivity, double> >(Key_Dialog_Router)
            .InstancePerLifetimeScope();

            builder
            .Register(c =>
            {
                var cc = c.Resolve <IComponentContext>();
                Func <IPostToBot> makeInner = () =>
                {
                    IPostToBot post = new ReactiveDialogTask(cc.Resolve <IDialogTask>(), cc.Resolve <Func <IDialog <object> > >());
                    post            = new ScoringDialogTask <double>(post, cc.ResolveKeyed <IScorable <IActivity, double> >(Key_Dialog_Router));
                    return(post);
                };

                IPostToBot outer = new PersistentDialogTask(makeInner, cc.Resolve <IBotData>());
                outer            = new SerializingDialogTask(outer, cc.Resolve <IAddress>(), c.Resolve <IScope <IAddress> >());
                outer            = new ExceptionTranslationDialogTask(outer);
                outer            = new LocalizedDialogTask(outer);
                outer            = new PostUnhandledExceptionToUserTask(outer, cc.Resolve <IBotToUser>(), cc.Resolve <ResourceManager>(), cc.Resolve <TraceListener>());
                outer            = new LogPostToBot(outer, cc.Resolve <IActivityLogger>());
                return(outer);
            })
            .As <IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <NullActivityLogger>()
            .AsImplementedInterfaces()
            .SingleInstance();

            builder
            .RegisterType <AlwaysSendDirect_BotToUser>()
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .Register(c => new LogBotToUser(
                          new MapToChannelData_BotToUser(c.Resolve <AlwaysSendDirect_BotToUser>(), new [] { new KeyboardCardMapper() }),
                          c.Resolve <IActivityLogger>()))
            .As <IBotToUser>()
            .InstancePerLifetimeScope();
        }
Example #31
0
 public void TestStudentService()
 {
     var studentService = AutofacResolver.Resolve <IStudentService>();
     var result         = studentService.GetAllStudentsResponse().ToList();
 }