Example #1
1
        public void Init() {
            _settingsA = new ShellSettings { Name = "Alpha" };
            _settingsB = new ShellSettings { Name = "Beta", };
            _routes = new RouteCollection();

            var rootBuilder = new ContainerBuilder();
            rootBuilder.Register(ctx => _routes);
            rootBuilder.RegisterType<ShellRoute>().InstancePerDependency();
            rootBuilder.RegisterType<RunningShellTable>().As<IRunningShellTable>().SingleInstance();
            rootBuilder.RegisterModule(new WorkContextModule());
            rootBuilder.RegisterType<WorkContextAccessor>().As<IWorkContextAccessor>().InstancePerMatchingLifetimeScope("shell");
            rootBuilder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>();
            rootBuilder.RegisterType<ExtensionManager>().As<IExtensionManager>();
            rootBuilder.RegisterType<StubCacheManager>().As<ICacheManager>();
            rootBuilder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>();
            rootBuilder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>();

            _rootContainer = rootBuilder.Build();

            _containerA = _rootContainer.BeginLifetimeScope(
                "shell",
                builder => {
                    builder.Register(ctx => _settingsA);
                    builder.RegisterType<RoutePublisher>().As<IRoutePublisher>().InstancePerMatchingLifetimeScope("shell");
                });

            _containerB = _rootContainer.BeginLifetimeScope(
                "shell",
                builder => {
                    builder.Register(ctx => _settingsB);
                    builder.RegisterType<RoutePublisher>().As<IRoutePublisher>().InstancePerMatchingLifetimeScope("shell");
                });
        }
        public void Init() {
            _contentDefinitionManager = new Mock<IContentDefinitionManager>();

            var builder = new ContainerBuilder();
            builder.RegisterType<DefaultContentManager>().As<IContentManager>();
            builder.RegisterType<DefaultContentManagerSession>().As<IContentManagerSession>();
            builder.RegisterInstance(_contentDefinitionManager.Object);
            builder.RegisterInstance(new Mock<IContentDisplay>().Object);

            builder.RegisterType<AlphaPartHandler>().As<IContentHandler>();
            builder.RegisterType<BetaPartHandler>().As<IContentHandler>();
            builder.RegisterType<GammaPartHandler>().As<IContentHandler>();
            builder.RegisterType<DeltaPartHandler>().As<IContentHandler>();
            builder.RegisterType<EpsilonPartHandler>().As<IContentHandler>();
            builder.RegisterType<FlavoredPartHandler>().As<IContentHandler>();
            builder.RegisterType<StyledHandler>().As<IContentHandler>();
            builder.RegisterType<DefaultShapeTableManager>().As<IShapeTableManager>();
            builder.RegisterType<ShapeTableLocator>().As<IShapeTableLocator>();
            builder.RegisterType<DefaultShapeFactory>().As<IShapeFactory>();
            builder.RegisterType<DefaultContentDisplay>().As<IContentDisplay>();

            builder.RegisterType<StubExtensionManager>().As<IExtensionManager>();

            builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>));

            _session = _sessionFactory.OpenSession();
            builder.RegisterInstance(new TestSessionLocator(_session)).As<ISessionLocator>();

            _container = builder.Build();
            _manager = _container.Resolve<IContentManager>();
        }
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            builder.RegisterType<ShippingByWeightService>().As<IShippingByWeightService>().InstancePerHttpRequest();

            //data layer
            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                //register named context
                builder.Register<IDbContext>(c => new ShippingByWeightObjectContext(dataProviderSettings.DataConnectionString))
                    .Named<IDbContext>("nop_object_context_shipping_weight_zip")
                    .InstancePerHttpRequest();

                builder.Register<ShippingByWeightObjectContext>(c => new ShippingByWeightObjectContext(dataProviderSettings.DataConnectionString))
                    .InstancePerHttpRequest();
            }
            else
            {
                //register named context
                builder.Register<IDbContext>(c => new ShippingByWeightObjectContext(c.Resolve<DataSettings>().DataConnectionString))
                    .Named<IDbContext>("nop_object_context_shipping_weight_zip")
                    .InstancePerHttpRequest();

                builder.Register<ShippingByWeightObjectContext>(c => new ShippingByWeightObjectContext(c.Resolve<DataSettings>().DataConnectionString))
                    .InstancePerHttpRequest();
            }

            //override required repository with our custom context
            builder.RegisterType<EfRepository<ShippingByWeightRecord>>()
                .As<IRepository<ShippingByWeightRecord>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_shipping_weight_zip"))
                .InstancePerHttpRequest();
        }
Example #4
0
        public static IContainer BuildContainer()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType<StatisticsViewModel>();
            builder.RegisterType<DetailsViewModel>();

            builder.RegisterType<MainView>();
            builder.RegisterType<MainViewModel>();
            builder.RegisterType<CameraView>();
            builder.RegisterType<CameraViewModel>();

            builder.RegisterType<MvxMessengerHub>().As<IMvxMessenger>().SingleInstance();
            builder.RegisterType<ApplicationDataRepository>().As<IApplicationDataRepository>();

            builder.RegisterAssemblyTypes(typeof(MyShuttleClient).Assembly)
                .Where(t => t.Name.EndsWith("Service"))
                .AsImplementedInterfaces();

            builder.RegisterAssemblyTypes(typeof(MyShuttleClient).Assembly)
                .Where(t => t.Name.EndsWith("ServiceSingleton"))
                .AsImplementedInterfaces().SingleInstance();

            builder.RegisterType<MyShuttleClient>().As<IMyShuttleClient>();

            return builder.Build();
        }
		private void RegisterContainer() {
			var builder = new ContainerBuilder();
			builder.RegisterControllers(Assembly.GetExecutingAssembly());
			_pluginServicee.Startup(builder);
			_container = builder.Build();
			DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));
		}
Example #6
0
        protected void Application_Start()
        {
            Database.SetInitializer(new TrainingDbInitializer());

            var builder = new ContainerBuilder();

            builder.RegisterType<EditableUserRepository>().As<IEditableRepository<User>>();
            builder.RegisterType<EditableSysOpRepository>().As<IEditableRepository<SysOp>>();
            builder.RegisterType<CompanyRepository>().As<IEditableRepository<Company>>();
            builder.RegisterType<CommentRepository>().As<IEditableRepository<Comment>>();
            builder.RegisterType<CourseRepository>().As<IEditableRepository<Course>>();
            builder.RegisterType<EmployeeCourseRepository>().As<IEditableRepository<EmployeeCourse>>();
            builder.RegisterType<DivisionRepository>().As<IEditableRepository<Division>>();
            builder.RegisterType<EmployeeRepository>().As<IEditableRepository<Employee>>();
            builder.RegisterType<EmployeeCourseStatusRepository>().As<IEditableRepository<EmployeeCourseStatus>>();
            builder.RegisterType<InstructorRepository>().As<IEditableRepository<Instructor>>();
            builder.RegisterType<RaceRepository>().As<IEditableRepository<Race>>();
            builder.RegisterType<RegionRepository>().As<IEditableRepository<Region>>();
            builder.RegisterType<ResultRepository>().As<IEditableRepository<Result>>();
            builder.RegisterType<EmployeeDocumentRepository>().As<IEditableRepository<EmployeeDocument>>();
            builder.RegisterType<TrainingScheduleRepository>().As<IEditableRepository<TrainingSchedule>>();
            builder.RegisterType<EmployeeTrainingScheduleRepository>().As<IEditableRepository<EmployeeTrainingSchedule>>();
            builder.RegisterType<TrainingManualRepository>().As<IEditableRepository<TrainingManual>>();
            builder.RegisterType<CompanyBudgetRepository>().As<IEditableRepository<CompanyBudget>>();
            builder.RegisterType<DivisionBudgetRepository>().As<IEditableRepository<DivisionBudget>>();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            GlobalConfiguration.Configure(WebApiConfig.Register);
            GlobalConfiguration.Configuration.MessageHandlers.Add(new BasicTrainingAuthMessageHandler());
        }
Example #7
0
        public static void Init()
        {
            var serviceBusConnectionString = ConfigurationManager.ConnectionStrings["ServiceBus"].ConnectionString;
            var builder = new ContainerBuilder();
            var typeProvider = new AssemblyScanningTypeProvider(
                   Assembly.GetAssembly(typeof(ExampleEventHandler)),
                   Assembly.GetAssembly(typeof(ExampleCommand))
                   );

            var applicationName = Assembly.GetExecutingAssembly().ToNimbusName();
            var instanceName = Environment.MachineName;

            builder.RegisterNimbus(typeProvider);
            builder.RegisterType<NimbusLogger>().As<ILogger>();
            builder.Register(componetContext => new BusBuilder()
                .Configure()
                .WithConnectionString(serviceBusConnectionString)
                .WithNames(applicationName, instanceName)
                .WithTypesFrom(typeProvider)
                .WithDefaultTimeout(TimeSpan.FromSeconds(30))
                .WithAutofacDefaults(componetContext)
                .Build())
                .As<IBus>()
                .AutoActivate()
                .OnActivated(o => o.Instance.Start())
                .SingleInstance();

            _container = builder.Build();
        }
Example #8
0
        public static void Configure()
        {
            var assemblies = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();
            var builder = new ContainerBuilder();

            builder.RegisterAssemblyTypes(assemblies)
                .Where(t => typeof(IStartable).IsAssignableFrom(t))
                .As<IStartable>()
                .SingleInstance();

            builder.RegisterAssemblyModules(assemblies);

            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            var container = builder.Build();

            // Set the dependency resolver for Web API.
            var webApiResolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

            // Set the dependency resolver for MVC.
            var mvcResolver = new AutofacDependencyResolver(container);
            DependencyResolver.SetResolver(mvcResolver);
        }
Example #9
0
        public static ContainerBuilder GetMinimalBuilder()
        {
            var builder = new ContainerBuilder();
            builder.Register(c => ReadAppConfigConfig()).SingleInstance();

            return builder;
        }
 public static void RegisterTypes()
 {
     var builder = new ContainerBuilder();
     builder.RegisterType<VideoRepository>().As<IVideoRepository>().InstancePerLifetimeScope();
     builder.RegisterType<OrderRepository>().As<IOrderRepository>().InstancePerLifetimeScope();
     builder.RegisterType<UserRepository>().As<IUserRepository>();
     builder.RegisterType<MockPaymentProcessor>().As<IPaymentProcessor>().InstancePerLifetimeScope();
     builder.RegisterType<StoreController>()
                         .UsingConstructor(typeof(IVideoRepository), typeof(IUserRepository));
     builder.RegisterType<CartController>()
                         .UsingConstructor(typeof(IVideoRepository));
     builder.RegisterType<WishlistController>()
                         .UsingConstructor(typeof(IUserRepository), typeof(IVideoRepository));
     builder.RegisterType<OrderController>()
                         .UsingConstructor(typeof(IVideoRepository), typeof(IOrderRepository), typeof(IUserRepository), typeof(IPaymentProcessor));
     builder.RegisterType<HomeController>()
                         .UsingConstructor(typeof(IVideoRepository), typeof(IOrderRepository), typeof(IUserRepository));
     builder.RegisterType<VideosController>()
                         .UsingConstructor(typeof(IVideoRepository));
     builder.RegisterType<OrdersController>()
                         .UsingConstructor(typeof(IOrderRepository));
     builder.RegisterType<UsersController>()
                         .UsingConstructor(typeof(IUserRepository));
     builder.RegisterType<AccountController>()
                         .UsingConstructor(typeof(IUserRepository));
     var container = builder.Build();
     var resolver = new AutofacDependencyResolver(container);
     DependencyResolver.SetResolver(resolver);
 }
Example #11
0
        private static void RegisterTypes(ContainerBuilder builder)
        {
            string baseDirectory = HttpContext.Current.Server.MapPath("~/App_Data") + ConfigurationManager.AppSettings["dataFolderName"];

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

            var repositoryAssemblies = Assembly.Load("FileRepository");
            builder.RegisterAssemblyTypes(repositoryAssemblies).AsImplementedInterfaces().WithParameter(new NamedParameter("path", baseDirectory));

            var serviceAssemblies = Assembly.Load("Services");
            builder.RegisterAssemblyTypes(serviceAssemblies).AsImplementedInterfaces();

            var configurationManagerWrapperAssembly = Assembly.Load("ConfigurationManagerWrapper");
            builder.RegisterAssemblyTypes(configurationManagerWrapperAssembly).AsImplementedInterfaces();

            var fileAssembly = Assembly.Load("SystemFileAdapter");
            builder.RegisterAssemblyTypes(fileAssembly).AsImplementedInterfaces();

            //builder.RegisterType<NLogLogger>().As<ILogger>();
            builder.Register(c => new NLogLogger()).As<ILogger>().InstancePerHttpRequest();
            builder.RegisterType<UserHub>();
            builder.RegisterType<TodoHub>();
            //            builder.RegisterModule(new ConfigurationSettingsReader("autofac"));
            builder.RegisterFilterProvider();
        }
Example #12
0
 public void Init(IEnumerable<Type> dataMigrations) {
    
     var builder = new ContainerBuilder();
     _folders = new StubFolders();
     var contentDefinitionManager = new Mock<IContentDefinitionManager>().Object;
     
     builder.RegisterInstance(new ShellSettings { DataTablePrefix = "TEST_"});
     
     builder.RegisterType<SqlServerDataServicesProvider>().As<IDataServicesProvider>();
     builder.RegisterType<DataServicesProviderFactory>().As<IDataServicesProviderFactory>();
     builder.RegisterType<NullInterpreter>().As<IDataMigrationInterpreter>();
     builder.RegisterInstance(_folders).As<IExtensionFolders>();
     builder.RegisterInstance(contentDefinitionManager).As<IContentDefinitionManager>();
     builder.RegisterType<ExtensionManager>().As<IExtensionManager>();
     builder.RegisterType<DataMigrationManager>().As<IDataMigrationManager>();
     builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>));
     builder.RegisterType<StubCacheManager>().As<ICacheManager>();
     builder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>();
     builder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>();
     _session = _sessionFactory.OpenSession();
     builder.RegisterInstance(new DefaultContentManagerTests.TestSessionLocator(_session)).As<ISessionLocator>().As<ITransactionManager>();
     foreach(var type in dataMigrations) {
         builder.RegisterType(type).As<IDataMigration>();
     }
     _container = builder.Build();
     _container.Resolve<IExtensionManager>();
     _dataMigrationManager = _container.Resolve<IDataMigrationManager>();
     _repository = _container.Resolve<IRepository<DataMigrationRecord>>();
     _transactionManager = _container.Resolve<ITransactionManager>();
     InitDb();
 }
Example #13
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterModule(new RepositoryModule());

            builder.RegisterType(typeof(SampleArchContext)).As(typeof(DbContext)).InstancePerLifetimeScope();
            builder.RegisterType(typeof(UnitOfWork)).As(typeof(IUnitOfWork)).InstancePerRequest();
        }
Example #14
0
 public void DictionaryDocument_Operations()
 {
     var builder = new ContainerBuilder();
     builder.RegisterModule(new SolrNetModule("http://localhost:8983/solr"));
     var container = builder.Build();
     var m = container.Resolve<ISolrOperations<Dictionary<string, object>>>();
 }
        public void TheyShouldBeResolvable()
        {
            var interceptorTypes = new[] {typeof (DummyInterceptor)};

            var builder = new ContainerBuilder();
            var typeProvider = Substitute.For<ITypeProvider>();
            typeProvider.InterceptorTypes.Returns(interceptorTypes);

            builder.RegisterNimbus(typeProvider);

            using (var container = builder.Build())
            using (var dependencyResolver = container.Resolve<IDependencyResolver>())
            using (var scope = dependencyResolver.CreateChildScope())
            {
                var interceptorSetting = new GlobalOutboundInterceptorTypesSetting
                                         {
                                             Value = interceptorTypes
                                         };
                var outboundInterceptorFactory = new OutboundInterceptorFactory(interceptorSetting,
                                                                                new PropertyInjector(Substitute.For<IClock>(),
                                                                                                     Substitute.For<IDispatchContextManager>(),
                                                                                                     Substitute.For<ILargeMessageBodyStore>()));

                var dummyNimbusMessage = new NimbusMessage("nullQueue");
                var interceptors = outboundInterceptorFactory.CreateInterceptors(scope, dummyNimbusMessage);

                interceptors.Count().ShouldBe(1);
            }
        }
        protected void Application_Start() {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);


            Store = new DocumentStore() { ConnectionStringName = "Onboarding" };
            Store.Initialize();
            var builder = new ContainerBuilder();

            Store.Conventions.RegisterIdConvention<User>((dbname, commands, user) => "users/" + user.UserName);

            builder.Register(c => {
                var store = new DocumentStore {
                    ConnectionStringName = "Onboarding",
                    DefaultDatabase = "Onboarding"
                }.Initialize();

                return store;

            }).As<IDocumentStore>().SingleInstance();

            builder.Register(c => c.Resolve<IDocumentStore>().OpenAsyncSession()).As<IAsyncDocumentSession>().InstancePerLifetimeScope();

        }
        public void Init() {
            var builder = new ContainerBuilder();
            //builder.RegisterModule(new ImplicitCollectionSupportModule());
            builder.RegisterType<MembershipService>().As<IMembershipService>();
            builder.RegisterType<DefaultContentQuery>().As<IContentQuery>();
            builder.RegisterType<DefaultContentManager>().As<IContentManager>();
            builder.RegisterType(typeof(SettingsFormatter))
                .As(typeof(IMapper<XElement, SettingsDictionary>))
                .As(typeof(IMapper<SettingsDictionary, XElement>));
            builder.RegisterType<ContentDefinitionManager>().As<IContentDefinitionManager>();
            builder.RegisterType<DefaultContentManagerSession>().As<IContentManagerSession>();
            builder.RegisterType<UserPartHandler>().As<IContentHandler>();
            builder.RegisterType<StubWorkContextAccessor>().As<IWorkContextAccessor>();
            builder.RegisterType<OrchardServices>().As<IOrchardServices>();
            builder.RegisterAutoMocking(MockBehavior.Loose);
            builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>));
            builder.RegisterInstance(new Mock<IMessageEventHandler>().Object);
            builder.RegisterType<DefaultMessageManager>().As<IMessageManager>();
            builder.RegisterType<DefaultShapeTableManager>().As<IShapeTableManager>();
            builder.RegisterType<DefaultShapeFactory>().As<IShapeFactory>();
            builder.RegisterType<StubExtensionManager>().As<IExtensionManager>();
            builder.RegisterType<DefaultContentDisplay>().As<IContentDisplay>();

            _session = _sessionFactory.OpenSession();
            builder.RegisterInstance(new TestSessionLocator(_session)).As<ISessionLocator>();
            _container = builder.Build();
            _membershipService = _container.Resolve<IMembershipService>();
        }
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<ViewFactory>().As<IViewFactory>().SingleInstance();
            builder.RegisterType<Navigator>().As<INavigator>().SingleInstance();
            builder.Register<INavigation>(ctx => App.Current.MainPage.Navigation).SingleInstance();

        }
Example #19
0
        /// <summary>
        /// Override to add registrations to the container.
        /// </summary>
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            Log.Trace("Registering Cyclops.DependencyInjection module");
            builder.RegisterCyclopsRepositories<PetstoreRepository>("PetstoreDatabase");
        }
Example #20
0
        public void Init() {
            _tempFolderName = Path.GetTempFileName();
            File.Delete(_tempFolderName);
            var assembly = GetType().Assembly;
            foreach (var name in assembly.GetManifestResourceNames()) {
                if (name.StartsWith(DataPrefix)) {
                    string text;
                    using (var stream = assembly.GetManifestResourceStream(name)) {
                        using (var reader = new StreamReader(stream))
                            text = reader.ReadToEnd();

                    }

                    // Pro filtering
                    var relativePath = name
                        .Substring(DataPrefix.Length)
                        .Replace(".txt", ":txt")
                        .Replace(".recipe.xml", ":recipe:xml")
                        .Replace('.', Path.DirectorySeparatorChar)
                        .Replace(":txt", ".txt")
                        .Replace(":recipe:xml", ".recipe.xml");

                    var targetPath = Path.Combine(_tempFolderName, relativePath);

                    Directory.CreateDirectory(Path.GetDirectoryName(targetPath));
                    using (var stream = new FileStream(targetPath, FileMode.Create)) {
                        using (var writer = new StreamWriter(stream)) {
                            writer.Write(text);
                        }
                    }
                }
            }

            var builder = new ContainerBuilder();
            var harvester = new ExtensionHarvester(new StubCacheManager(), new StubWebSiteFolder(), new Mock<ICriticalErrorProvider>().Object);
            _folders = new ModuleFolders(new[] { _tempFolderName }, harvester);
            builder.RegisterType<RecipeManager>().As<IRecipeManager>();
            builder.RegisterType<RecipeHarvester>().As<IRecipeHarvester>();
            builder.RegisterType<RecipeStepExecutor>().As<IRecipeStepExecutor>();
            builder.RegisterType<StubStepQueue>().As<IRecipeStepQueue>().InstancePerLifetimeScope();
            builder.RegisterType<StubRecipeJournal>().As<IRecipeJournal>();
            builder.RegisterType<StubRecipeScheduler>().As<IRecipeScheduler>();
            builder.RegisterType<ExtensionManager>().As<IExtensionManager>();
            builder.RegisterType<StubAppDataFolder>().As<IAppDataFolder>();
            builder.RegisterType<StubClock>().As<IClock>();
            builder.RegisterType<StubCacheManager>().As<ICacheManager>();
            builder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>();
            builder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>();
            builder.RegisterInstance(_folders).As<IExtensionFolders>();
            builder.RegisterInstance(new Mock<IRecipeExecuteEventHandler>().Object);
            builder.RegisterType<Environment.Extensions.ExtensionManagerTests.StubLoaders>().As<IExtensionLoader>();
            builder.RegisterType<RecipeParser>().As<IRecipeParser>();
            builder.RegisterType<StubWebSiteFolder>().As<IWebSiteFolder>();
            builder.RegisterType<CustomRecipeHandler>().As<IRecipeHandler>();

            _container = builder.Build();
            _recipeManager = _container.Resolve<IRecipeManager>();
            _recipeParser = _container.Resolve<IRecipeParser>();
            _recipeHarvester = _container.Resolve<IRecipeHarvester>();
        }
Example #21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            // Create the Autofac container builder.
            var builder = new ContainerBuilder();
            // Add any Autofac modules or registrations.
            builder.RegisterModule(new ServiceModule());
            // Populate the services.
            builder.Populate(services);
            // Build the container.
            var container = builder.Build();
            // Resolve and return the service provider.
            return container.Resolve<IServiceProvider>();
        }
        public static void Configure()
        {
            var builder = new ContainerBuilder();

            var config = GlobalConfiguration.Configuration;

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            //builder.RegisterWebApiFilterProvider(config);
            var dbPath = WebConfigurationManager.AppSettings["sqLiteDb"].Replace(@"~\", "");
            bool useDiskConnOnlyValue;
            if (!bool.TryParse(WebConfigurationManager.AppSettings["useDiskConnOnly"], out useDiskConnOnlyValue))
            {
                throw new InvalidOperationException("Invalid useDiskCOnnOnly in web.config");
            }

            var lucenceIndeDirectory = WebConfigurationManager.AppSettings["lucenceIndeDirectory"].Replace(@"~\", "");

            builder.RegisterModule(new LuceneIndexModule(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, lucenceIndeDirectory)));

            builder.RegisterModule(new ConnectionManagerModule(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, dbPath), useDiskConnOnlyValue));
            builder.RegisterModule(new LocationControllerModule());

            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
        public static void RegisterAutofac()
        {
            var builder = new ContainerBuilder();

            // Register your MVC controllers.
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            // OPTIONAL: Register model binders that require DI.
            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
            builder.RegisterModelBinderProvider();

            // OPTIONAL: Register web abstractions like HttpContextBase.
            builder.RegisterModule<AutofacWebTypesModule>();

            // OPTIONAL: Enable property injection in view pages.
            builder.RegisterSource(new ViewRegistrationSource());

            // OPTIONAL: Enable property injection into action filters.
            builder.RegisterFilterProvider();

            // Register services
            RegisterServices(builder);

            // Set the dependency resolver to be Autofac.
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Example #24
0
        static void Main(string[] args)
        {
            var containerBuilder = new ContainerBuilder();

            containerBuilder.RegisterType<Cpu>().As<ICpu>().SingleInstance();
            containerBuilder.RegisterType<Emulator>().As<IEmulator>();
            containerBuilder.RegisterType<Memory>().As<IMemory>().SingleInstance();
            containerBuilder.RegisterType<Ppu>().As<IPpu>();

            var instructionTypes = Assembly.GetExecutingAssembly().GetTypes().Where(f => typeof(IInstruction).IsAssignableFrom(f) && !f.IsAbstract).ToArray();

            containerBuilder.RegisterTypes(instructionTypes)
                .As<IInstruction>();

            var container = containerBuilder.Build();

            var emulator = container.Resolve<IEmulator>();
            var memory = container.Resolve<IMemory>();
            memory.SetCartridge(new Cartridge("../../roms/nestest.nes"));
            emulator.Reset();
            for (;;)
            {
                emulator.Step();
            }
        }
Example #25
0
 protected override void Load(ContainerBuilder builder)
 {
     throw new NotImplementedException();
     //builder.RegisterAssemblyTypes(typeof(GenericRepository).Assembly)
     //    .Where(x => x.Name.EndsWith("Repository"))
     //    .AsImplementedInterfaces();
 }
Example #26
0
    protected void Application_Start()
    {
        #region ApplicationStart

        ContainerBuilder builder = new ContainerBuilder();

        // Register your MVC controllers.
        builder.RegisterControllers(typeof(MvcApplication).Assembly);

        // Set the dependency resolver to be Autofac.
        IContainer container = builder.Build();

        BusConfiguration busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.MvcInjection.WebApplication");
        // ExistingLifetimeScope() ensures that IBus is added to the container as well,
        // allowing you to resolve IBus from your own components.
        busConfiguration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container));
        busConfiguration.UseSerialization<JsonSerializer>();
        busConfiguration.UsePersistence<InMemoryPersistence>();
        busConfiguration.EnableInstallers();

        bus = Bus.CreateSendOnly(busConfiguration);

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);

        #endregion
    }
Example #27
0
        public void FactoryMethodWillCreateShellRoutes() {
            var settings = new ShellSettings { Name = "Alpha" };
            var builder = new ContainerBuilder();
            builder.RegisterType<ShellRoute>().InstancePerDependency();
            builder.RegisterAutoMocking();
            builder.Register(ctx => settings);

            var container = builder.Build();
            var buildShellRoute = container.Resolve<Func<RouteBase, ShellRoute>>();

            var routeA = new Route("foo", new MvcRouteHandler());
            var route1 = buildShellRoute(routeA);

            var routeB = new Route("bar", new MvcRouteHandler()) {
                DataTokens = new RouteValueDictionary { { "area", "Beta" } }
            };
            var route2 = buildShellRoute(routeB);

            Assert.That(route1, Is.Not.SameAs(route2));

            Assert.That(route1.ShellSettingsName, Is.EqualTo("Alpha"));
            Assert.That(route1.Area, Is.Null);

            Assert.That(route2.ShellSettingsName, Is.EqualTo("Alpha"));
            Assert.That(route2.Area, Is.EqualTo("Beta"));
        }
Example #28
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<Foo>();
            builder.RegisterAndActivate<ScopeFactory<Foo>>();

            Console.WriteLine("MyModule.Load()");
        }
        // Configure is called after ConfigureServices is called.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            var builder = new ContainerBuilder();
            
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>();

            //app.UseCookieAuthentication(options =>
            //{
            //    options.AuthenticationScheme = "Temp";
            //    options.AutomaticAuthentication = false;
            //}, "external");

            // Configure the HTTP request pipeline.
            //app.UseStaticFiles();


            // Add the following route for porting Web API 2 controllers.
            // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            app.UseOAuthBearerAuthentication(options =>
            {
                options.Authority = "https://localhost:44333/core";
                //options.Authority = "https://karamaidentityserver.azurewebsites.net/core";
                options.Audience = "https://karama.com/resources";
                options.AutomaticAuthentication = true;                
            });

            app.UseMiddleware<RequiredScopesMiddleware>(new List<string> { "api3" });

            app.UseCors("AllowSpecificOrigins");


            // Add MVC to the request pipeline.
            app.UseMvc();
        }
        public void ResolveSolrOperations_withMultiCore()
        {
            // Arrange
            var builder = new ContainerBuilder();
            var cores = new SolrServers {
                                new SolrServerElement {
                                        Id = "entity1",
                                        DocumentType = typeof (Entity1).AssemblyQualifiedName,
                                        Url = "http://localhost:8983/solr/coreEntity1",
                                    },
                               new SolrServerElement {
                                        Id = "entity2",
                                        DocumentType = typeof (Entity2).AssemblyQualifiedName,
                                        Url = "http://localhost:8983/solr/coreEntity2",
                                },
                            };

            builder.RegisterModule(new SolrNetModule(cores));
            var container = builder.Build();

            // Act
            var solrOperations1 = container.Resolve<ISolrOperations<Entity1>>();
            var solrOperations2 = container.Resolve<ISolrOperations<Entity2>>();

            // Assert
            Assert.IsTrue(solrOperations1 is SolrServer<Entity1>);
            Assert.IsTrue(solrOperations2 is SolrServer<Entity2>);
        }