Build() public method

public Build ( ) : IContainer
return IContainer
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Autofac Configuration
            var builder = new Autofac.ContainerBuilder();

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

            builder.RegisterModule(new RepositoryModule());
            builder.RegisterModule(new ServiceModule());
            builder.RegisterModule(new EFModule());
            builder.RegisterModule(new ViewModelModule());

            builder.RegisterType(typeof(NavigationService)).As(typeof(INavigationService)).InstancePerRequest();

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

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Beispiel #2
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");
                });
        }
Beispiel #3
0
        protected void BuildContainer()
        {
            var builder = new Autofac.ContainerBuilder();

            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();

            builder.RegisterAssemblyTypes(typeof(ChangeNameCommandHandler).Assembly).Where(x => x.Name.EndsWith("Handler")).AsImplementedInterfaces();

            RegisterMediatr(builder);

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

            DependencyResolver.SetResolver(new AutofacDependencyResolver(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));
        }
Beispiel #5
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());
        }
        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);
        }
Beispiel #7
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();
 }
Beispiel #8
0
        public Bootstrapper()
        {
            Naru.Core.UnhandledExceptionHandler.InstallDomainUnhandledException();
            Naru.TPL.UnhandledExceptionHandler.InstallTaskUnobservedException();

            IContainer container = null;

            var builder = new ContainerBuilder();

            builder.RegisterModule(new Log4NetModule
                                            {
                                                SectionName = "CommonLogging.Nitrogen.Server"
                                            });

            builder.RegisterModule(new AgathaServerModule
                                   {
                                       ContainerFactory = () => container,
                                       HandlerAssembly = typeof(AssemblyHook).Assembly,
                                       RequestResponseAssembly = typeof(Common.AssemblyHook).Assembly
                                   });

            container = builder.Build();

            Console.WriteLine("EndPoint - {0}", END_POINT);

            var baseAddress = new Uri(END_POINT);
            Host = new ServiceHost(typeof(WcfRequestProcessor), baseAddress);
            Host.Open();
        }
Beispiel #9
0
        public Bootstrapper()
        {
            IContainer container = null;

            var builder = new ContainerBuilder();

            builder.RegisterModule(new AgathaClientModule
                                   {
                                       ContainerFactory = () => container,
                                       RequestResponseAssembly = typeof (Nitrogen.Common.AssemblyHook).Assembly
                                   });

            builder.RegisterModule(new Log4NetModule {SectionName = "CommonLogging.Nitrogen.Client"});

            builder.RegisterType<MessageStream>().As<IMessageStream>().SingleInstance();

            builder.RegisterType<ShellViewModel>().AsSelf();

            builder.RegisterModule(new WPFModule());
            builder.RegisterType<WPFStartable>().AsSelf();

            builder.RegisterType<ClientStartable>().AsSelf();

            // DataExplorer
            builder.RegisterModule(new DataExplorerModule());
            builder.RegisterType<DataExplorerStartable>().AsSelf();

            // Build the container
            container = builder.Build();

            // TODO : Ideally change this, so it isn't resolved like this
            container.Resolve<WPFStartable>().Start();
            container.Resolve<ClientStartable>().Start();
            container.Resolve<DataExplorerStartable>().Start();
        }
Beispiel #10
0
        public static void Run()
        {
            var builder = new Autofac.ContainerBuilder();
            var config = GlobalConfiguration.Configuration;
            var service = builder.RegisterType<FormularioService>()
                .As<IFormularioService>();

            var factory = builder.RegisterType<DatabaseFactoryFormulario>()
                .As<IDatabaseFactory>();

            var unit = builder.RegisterType<UnitOfWorkGeneric>()
                .As<IUnitOfWOrkGeneric<IDatabaseFactory>>();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            builder.RegisterWebApiFilterProvider(config);

            builder.RegisterWebApiModelBinderProvider();

            service.InstancePerRequest();
            factory.InstancePerRequest();
            unit.InstancePerRequest();


            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            config.Formatters.Remove(config.Formatters.XmlFormatter);

            var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
            json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
Beispiel #11
0
        public Container(IServiceCollection services)
        {
            // Create the container builder.
            autofacContainerBuilder = new Autofac.ContainerBuilder();

            // Register dependencies, populate the services from
            // the collection, and build the container. If you want
            // to dispose of the container at the end of the app,
            // be sure to keep a reference to it as a property or field.
            //builder.RegisterType<MyType>().As<IMyTyHippe>();

            //If nothing is using/calling a type in an assembly you are trying to load,
            //Load(...) will fail. The compiler will optimize the code so that unused dependencies
            //are removed.

            var assembly = Assembly.Load(new AssemblyName {
                Name = "Authentication.Container"
            });

            autofacContainerBuilder.RegisterAssemblyModules(assembly);

            autofacContainerBuilder.Populate(services);
            autofacContainer = autofacContainerBuilder.Build();

            serviceProvider = new AutofacServiceProvider(autofacContainer);
        }
Beispiel #12
0
        /// <summary>
        /// WebApi的AutoFac配置
        /// </summary>
        /// <param name="projectName">WebApi项目名(命名空间)</param>
        public static void Init_WebApi(string projectName = "")
        {
            //默认项目名称
            projectName = string.IsNullOrEmpty(projectName) ? _DefaultApiName : projectName;
            //构造一个AutoFac的builder容器
            ContainerBuilder builder = new Autofac.ContainerBuilder();
            var configuration        = GlobalConfiguration.Configuration;

            builder.RegisterWebApiFilterProvider(configuration);

            Assembly apicontrollerAss = Assembly.Load(projectName);

            builder.RegisterApiControllers(apicontrollerAss);

            Assembly repositoryAss = Assembly.Load("Services");   //加载数据层程序集。

            Type[] rtypes = repositoryAss.GetTypes();
            builder.RegisterTypes(rtypes)
            .AsImplementedInterfaces().InstancePerApiRequest();

            //创建AutoFac工作容器
            var container = builder.Build();

            configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);//注册api容器
        }
Beispiel #13
0
        public static string _DefaultApiName = "O.AdminProApi"; //默认WebApi命名空间/项目名
        /// <summary>
        /// Web项目配置
        /// </summary>
        /// <param name="projectName">WebApi项目名(命名空间)</param>
        public static void Init(string projectName = "")
        {
            //默认项目名称
            projectName = string.IsNullOrEmpty(projectName) ? _DefaultName : projectName;

            //构造一个AutoFac的builder容器
            ContainerBuilder builder = new Autofac.ContainerBuilder();

            //第二步:告诉AutoFac控制器工厂,控制器类的创建去哪些程序集中查找(默认控制器工厂是去扫描bin目录下的所有程序集)
            Assembly controllerAss = Assembly.Load(projectName);

            builder.RegisterControllers(controllerAss);

            //加载业务逻辑层程序集。
            Assembly servicesAss = Assembly.Load("Services");

            Type[] stypes = servicesAss.GetTypes();
            builder.RegisterTypes(stypes).AsImplementedInterfaces(); //指明创建的stypes这个集合中所有类的对象实例,以其接口的形式保存

            //创建一个真正的AutoFac的工作容器
            var container = builder.Build();

            //将当前容器中的控制器工厂替换掉MVC默认的控制器工厂。
            //(即:不要MVC默认的控制器工厂了,用AutoFac容器中的控制器工厂替代)此处使用的是将AutoFac工作容器交给MVC底层 (需要using System.Web.Mvc;)
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Beispiel #14
0
        public static void Register()
        {
            var cb = new Autofac.ContainerBuilder();

            cb.RegisterType <QuizDbContext>().InstancePerRequest();
            cb.RegisterType <Repo <Quiz> >().As <IRepo <Quiz> >().InstancePerRequest();
            cb.RegisterType <Repo <Question> >().As <IRepo <Question> >().InstancePerRequest();
            cb.RegisterType <Repo <Answer> >().As <IRepo <Answer> >().InstancePerRequest();
            cb.RegisterType <Repo <QuizCategory> >().As <IRepo <QuizCategory> >().InstancePerRequest();
            cb.RegisterType <Repo <QuizRating> >().As <IRepo <QuizRating> >().InstancePerRequest();
            cb.RegisterType <Repo <QuizResult> >().As <IRepo <QuizResult> >().InstancePerRequest();
            cb.RegisterType <Repo <ContactInfo> >().As <IRepo <ContactInfo> >().InstancePerRequest();
            cb.RegisterType <Repo <UserActivity> >().As <IRepo <UserActivity> >().InstancePerRequest();

            cb.RegisterType <QuizService>().As <IQuizService>().InstancePerRequest();
            cb.RegisterType <QuestionService>().As <IQuestionService>().InstancePerRequest();
            cb.RegisterType <AnswerService>().As <IAnswerService>().InstancePerRequest();
            cb.RegisterType <QuizCategoryService>().As <IQuizCategoryService>().InstancePerRequest();
            cb.RegisterType <QuizResultService>().As <IQuizResultService>().InstancePerRequest();
            cb.RegisterType <UserActivityService>().As <IUserActivityService>().InstancePerRequest();

            cb.RegisterType <ModelConverter>().InstancePerRequest();
            cb.RegisterType <ViewModelConverter>().InstancePerRequest();

            cb.RegisterControllers(typeof(MvcApplication).Assembly).InstancePerRequest();
            cb.RegisterType <AccountController>().InstancePerDependency();
            cb.RegisterAssemblyModules(typeof(MvcApplication).Assembly);

            var container = cb.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Beispiel #15
0
        /// <summary>
        /// 注册
        /// </summary>
        public static AutofacWebApiDependencyResolver Register()
        {
            ContainerBuilder builder = new Autofac.ContainerBuilder();

            // Assembly controllerAss = Assembly.Load(string.Format("{0}.Web", proname));

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

            Assembly repositoryAss = Assembly.Load("serviceimpl");

            Type[] rtypes = repositoryAss.GetTypes();

            builder.RegisterTypes(rtypes)
            .AsImplementedInterfaces();

            // builder.RegisterTypes(typeof(SIC_WebClient)).SingleInstance().PropertiesAutowired();

            var container = builder.Build();

            // DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            // Set the dependency resolver for Web API.
            return(new AutofacWebApiDependencyResolver(container));
            //GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;
        }
Beispiel #16
0
        /// <summary>
        /// Configuration routine of the autofac container.
        /// </summary>
        /// <param name="eventBus">The event bus.</param>
        /// <param name="hoardeManager">The hoarde manager.</param>
        /// <param name="configurationManager">The host's configuration manager.</param>
        public static void Configure(IEventBus eventBus, ServiceModel.IHoardeManager hoardeManager, INutConfiguration configurationManager)
        {
            var builder = new ContainerBuilder();

            builder.RegisterInstance(eventBus);
            builder.RegisterInstance(hoardeManager);
            builder.RegisterInstance(configurationManager);

            builder.RegisterType<ServiceModel.ServicesManager>().AsImplementedInterfaces().SingleInstance();
            builder.RegisterType<ServiceModel.PollingClientCollection>().AsSelf().SingleInstance();
            builder.RegisterType<ServiceModel.RegisteredPackagesPollingClient>().AsSelf().SingleInstance();
            builder.RegisterType<ServiceModel.ReleasesPollingClient>();
            builder.RegisterType<ConfigurationManagement.DbConfigurationSettings>();

            // we will apply most of the configuration in one or more assembly modules.
            builder.RegisterAssemblyModules(typeof(AutofacConfig).Assembly);

            switch (configurationManager.Mode)
            {
                case ExecutionMode.Development:
                    builder.RegisterType<Repositories.OnDisk.OnDiskPackageRepository>().AsImplementedInterfaces().InstancePerLifetimeScope();
                    break;
                case ExecutionMode.Production:
                    builder.RegisterType<Repositories.SQLiteRepositories.PackageRepository>().AsImplementedInterfaces().InstancePerLifetimeScope();
                    break;
                default:
                    builder.RegisterType<Repositories.SQLiteRepositories.PackageRepository>().AsImplementedInterfaces().InstancePerLifetimeScope();
                    _log.WarnFormat("Unknown execution mode '{mode}'.  Registered Sqlite Repository.", configurationManager.Mode);
                    break;
            }

            _container = builder.Build();
        }
Beispiel #17
0
        private void configureIoC()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            builder.Register(ctx => LogManager.GetLogger("trace"))
                .As<Logger>()
                .InstancePerHttpRequest();

            builder.RegisterType<ProcessRunner>()
                .AsImplementedInterfaces()
                .InstancePerDependency()
                ;

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

            builder.RegisterType<Ansi2HtmlConverter>()
                .AsImplementedInterfaces()
                .InstancePerDependency()
                ;

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Beispiel #18
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Autofac Configuration
            var config = GlobalConfiguration.Configuration;

            var builder = new Autofac.ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            //builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();


            builder.RegisterModule(new ServiceModule());
            builder.RegisterModule(new EFModule());

            //var container = builder.Build();

            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            //config.DependencyResolver = new au
            //DependencyResolver.SetResolver(new AutofacWebApiDependencyResolver(container));
        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Register: create and configure the container
            _container = BootstrapContainer();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));

            var builder = new ContainerBuilder();

            //var configurationRepository =
            //    new ConfigurationRepository.ConfigurationRepository() as IConfigurationRepository;

            //builder.Register(c => configurationRepository).As<IConfigurationRepository>().SingleInstance();

            builder.RegisterType<StashCoreApiConsumer>().As<IStashCoreApiConsumer>();

            builder.RegisterType<PullTrackerRepository>().As<IPullTrackerRepository>();

            builder.RegisterType<RequestProcessFacade>().As<IRequestProcessFacade>();

            IContainer localContainer = builder.Build();

            AutofacHelper.Scope = localContainer;

            _containerProvider = new ContainerProvider(localContainer);
        }
Beispiel #20
0
        /// <summary>
        /// 普通的容器用法
        /// </summary>
        static void DI()
        {
            Autofac.ContainerBuilder containerBuilder = new Autofac.ContainerBuilder();
            //单例模式
            containerBuilder.RegisterType <DaoImpl>()
            .As <Dao>()
            .SingleInstance();

            //一个生命周期一个实例
            //containerBuilder.RegisterType<OrderService>()
            //    .As<IOrderService>()
            //    .InstancePerLifetimeScope();

            //每一次被请求都是一个实例
            //containerBuilder.RegisterType<OrderService>()
            //    .As<IOrderService>()
            //    .InstancePerDependency();

            var container = containerBuilder.Build();

            for (int j = 0; j < 2; j++)
            {
                using (var life = container.BeginLifetimeScope())
                {
                    for (int i = 0; i < 2; i++)
                    {
                        var service = life.Resolve <Dao>();
                        Console.WriteLine($"{service.Id}");
                    }
                }
            }
        }
        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>();
        }
Beispiel #22
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            AutoMapperConfiguration.Configure();

            //Autofac Configuration
            var builder = new Autofac.ContainerBuilder();


            builder.RegisterType <GameController>().InstancePerRequest();
            builder.RegisterType <PlayerController>().InstancePerRequest();
            builder.RegisterType <TeamController>().InstancePerRequest();
            builder.RegisterType <StatTypeController>().InstancePerRequest();
            builder.RegisterType <PositionController>().InstancePerRequest();
            builder.RegisterType <StatLineController>().InstancePerRequest();
            builder.RegisterType <AccountController>().InstancePerRequest();

            builder.RegisterModule(new RepositoryModule());
            builder.RegisterModule(new ServiceModule());
            builder.RegisterModule(new EFModule());

            var container = builder.Build();

            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
 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);
 }
Beispiel #24
0
        public async Task RouteAnUnknownIntentToTheDefaultHandler()
        {
            var containerBuilder    = new Autofac.ContainerBuilder();
            var httpResponseMessage = new Mock <IHttpResponseMessage>();
            var httpResponseTask    = Task.Run(() => httpResponseMessage.Object);

            httpResponseMessage.SetupGet(m => m.Content).Returns(_routesJson);

            var httpProxy = new Mock <IHttpProxy>();

            httpProxy.Setup(p => p.GetAsync(It.IsAny <string>(), It.IsAny <IEnumerable <KeyValuePair <string, string> > >())).Returns(httpResponseTask);
            containerBuilder.RegisterInstance <IHttpProxy>(httpProxy.Object);

            var cmdProcessor = new Mock <ICommandProcessor>(MockBehavior.Loose);

            containerBuilder.RegisterInstance <ICommandProcessor>(cmdProcessor.Object);

            var serviceProvider = new AutofacServiceProvider(containerBuilder.Build());

            var request = new UserRequestBuilder().Random().Build();
            var target  = new DataServiceRouter.Engine(serviceProvider, string.Empty);
            var actual  = await target.HandleRequestAsync(request);

            cmdProcessor.Verify(p => p.ProcessAsync("abcdefg", It.IsAny <UserRequest>()), Times.Once);
        }
    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
    }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //ModelBinders.Binders.DefaultBinder = new CustomModelBinder();

            //Autofac Configuration
            var builder = new Autofac.ContainerBuilder();

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


            builder.RegisterModule(new ServiceModule());
            builder.RegisterModule(new EFModule());

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());
        }
Beispiel #27
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 IContainer BuildContainer()
        {
            var builder = new Autofac.ContainerBuilder();

            RegisterDependencies(builder);
            return(builder.Build());
        }
Beispiel #29
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Autofac Configuration
            var builder = new Autofac.ContainerBuilder();

            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            builder.RegisterModelBinders(typeof(MvcApplication).Assembly);
            builder.RegisterModelBinderProvider();
            builder.RegisterModule(new RepositoryModule());

            builder.RegisterModule(new ServiceModule());
            builder.RegisterModule(new EFModule());
            builder.RegisterModule(new LoggingModule());
            builder.RegisterModule(new AutoMapperModule());
            //builder.RegisterModule(new RedisModule());

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
        }
Beispiel #30
0
        public static IContainer BuildOne()
        {
            Dictionary <string, string> pepe = new Dictionary <string, string>();
            string     pepito    = pepe.First().Key;
            IContainer container = null;

            try
            {
                Autofac.ContainerBuilder containerBuilder = new Autofac.ContainerBuilder();
                containerBuilder.RegisterType <Robot>().As <IMachine>();
                containerBuilder.Register((name, value) =>
                {
                    IMachine machine;
                    if (value.Named <string>("function").Trim().ToLower() == "transport")        /// It should be an enum type
                    {
                        machine = new Drone();
                    }
                    else
                    {
                        machine = new Robot();
                    }

                    return(machine);
                }).As <IMachine>();
                //builder.RegisterType<Drone>()
                //    .As<IMachine>()
                //    .As<IGun>()
                //    .IfNotRegistered(typeof(IMachine));
                container = containerBuilder.Build();
            }
            catch { throw new Exception("Container Exception"); }
            return(container);
        }
        public void Init()
        {
            _users = new List<UserEntity>();
            for (var ndx = 0; ndx < 10; ++ndx)
            {
                var postfix = ndx.ToString();
                var user = new UserEntity
                {
                    UserEntityId = ndx + 1,
                    DateRegistered = ServerTime.Now,
                    UserName = "******" + postfix,
                    Email = String.Format("user.{0}@test.com", ndx)
                };

                _users.Add(user);
            }

            Mapper.CreateMap<UserEntity, User>()
                .ForMember(p => p.Id, opt => opt.MapFrom(src => src.UserEntityId))
                .IgnoreAllNonExisting();

            var builder = new ContainerBuilder();

            builder.RegisterType<QueryBuilder>().As<IQueryBuilder>();
            var entitiesRepo = new Repository<UserEntity>(_users);
            var usersRepo = new Repository<User>(_users.Select(p
                => p.MapTo<User>()));

            builder.RegisterInstance(entitiesRepo).As<IRepository<UserEntity>>().SingleInstance();
            builder.RegisterInstance(usersRepo).As<IRepository<User>>().SingleInstance();

            var container = builder.Build();
            var resolver = new AutofacDependencyResolver(container);
            DependencyResolver.SetResolver(resolver);
        }
Beispiel #32
0
        protected void Application_Start()
        {
            //Autofac Configuration
            var builder = new Autofac.ContainerBuilder();

            builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();
            builder.RegisterModule(new ServiceModule());
            builder.RegisterModule(new EFModule());
            builder.RegisterModule(new AutofacWebTypesModule());
            builder.RegisterModule(new HelperModule());
            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            //Automapper
            AutoMapperConfiguration.Configure();

            log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //register BForms validation provider
            ModelValidatorProviders.Providers.Add(new BsModelValidatorProvider());
            BForms.Utilities.BsResourceManager.Register(Resources.Resources.ResourceManager);
        }
Beispiel #33
0
        /// <summary>
        /// Configures the multitenant dependency container.
        /// </summary>
        private static IContainer ConfigureDependencies()
        {
            // Register default dependencies in the application container.
            var builder = new ContainerBuilder();
            builder.RegisterType<Consumer>().As<IDependencyConsumer>().InstancePerDependency();
            builder.RegisterType<BaseDependency>().As<IDependency>().SingleInstance();
            var appContainer = builder.Build();

            // Create the multitenant container.
            var mtc = new MultitenantContainer(_tenantIdentifier, appContainer);

            // Configure overrides for tenant 1. Tenant 1 registers their dependencies
            // as instance-per-dependency.
            mtc.ConfigureTenant('1', b => b.RegisterType<Tenant1Dependency>().As<IDependency>().InstancePerDependency());

            // Configure overrides for tenant 2. Tenant 2 registers their dependencies
            // as singletons.
            mtc.ConfigureTenant('2', b => b.RegisterType<Tenant2Dependency>().As<IDependency>().SingleInstance());

            // Configure overrides for the default tenant. That means the default
            // tenant will have some different dependencies than other unconfigured
            // tenants.
            mtc.ConfigureTenant(null, b => b.RegisterType<DefaultTenantDependency>().As<IDependency>().SingleInstance());

            return mtc;
        }
Beispiel #34
0
        private static IContainer GetContainer()
        {
            var container = new Autofac.ContainerBuilder();

            container.RegisterAssemblyModules(Assembly.Load("ToolkitSample.DataAccess"));
            return(container.Build());
        }
        public static void Setup()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
            builder.RegisterModelBinderProvider();
            builder.RegisterModule<AutofacWebTypesModule>();
            builder.RegisterSource(new ViewRegistrationSource());
            builder.RegisterFilterProvider();
            builder.RegisterType<PremiumCalculationService>().As<IPremiumCalculationService>();
            builder.Register(context => new MapperConfiguration(configuration =>
            {
                configuration.AddProfile(new AutoMapperProfile());
            }))
               .AsSelf()
               .SingleInstance();

            builder.Register(context => context.Resolve<MapperConfiguration>()
                .CreateMapper(context.Resolve))
                .As<IMapper>()
                .InstancePerLifetimeScope();

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Beispiel #36
0
        public void Configuration(IAppBuilder app)
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            //Autofac Configuration
            var builder = new Autofac.ContainerBuilder();

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


            builder.RegisterModule(new ServiceModule());
            builder.RegisterModule(new EFModule());

            var container = builder.Build();

            //DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // Set the dependency resolver for MVC.
            var mvcResolver = new AutofacDependencyResolver(container);

            DependencyResolver.SetResolver(mvcResolver);

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

            GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

            ApplicationContainer.Container = container;
        }
        public void Init() {
            var builder = new ContainerBuilder();
            // builder.RegisterModule(new ImplicitCollectionSupportModule());
            builder.RegisterModule(new ContentModule());
            builder.RegisterType<DefaultContentManager>().As<IContentManager>().SingleInstance();
            builder.RegisterType<DefaultContentManagerSession>().As<IContentManagerSession>();

            builder.RegisterType<AlphaHandler>().As<IContentHandler>();
            builder.RegisterType<BetaHandler>().As<IContentHandler>();
            builder.RegisterType<GammaHandler>().As<IContentHandler>();
            builder.RegisterType<DeltaHandler>().As<IContentHandler>();
            builder.RegisterType<EpsilonHandler>().As<IContentHandler>();
            builder.RegisterType<FlavoredHandler>().As<IContentHandler>();
            builder.RegisterType<StyledHandler>().As<IContentHandler>();

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

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

            _session.Delete(string.Format("from {0}", typeof(GammaRecord).FullName));
            _session.Delete(string.Format("from {0}", typeof(DeltaRecord).FullName));
            _session.Delete(string.Format("from {0}", typeof(EpsilonRecord).FullName));
            _session.Delete(string.Format("from {0}", typeof(ContentItemVersionRecord).FullName));
            _session.Delete(string.Format("from {0}", typeof(ContentItemRecord).FullName));
            _session.Delete(string.Format("from {0}", typeof(ContentTypeRecord).FullName));
            _session.Flush();
            _session.Clear();

            _container = builder.Build();
            _manager = _container.Resolve<IContentManager>();

        }
Beispiel #38
0
        static int Main(string[] args)
        {
            var options = ParseCommandLine(args);

            if (options == null)
            {
                return(1);
            }

            var logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.ColoredConsole()
                         .CreateLogger();

            var builder = new Autofac.ContainerBuilder();

            builder.RegisterType <TestClient>().As <ITestApi>();
            builder.RegisterInstance(logger).As <ILogger>();
            builder.RegisterInstance(options).As <IProgramOptions>();
            builder.RegisterType <TestClient>().AsSelf();
            //builder.RegisterType<SignalRClient>().AsSelf();

            using (var container = builder.Build())
            {
                Run(container).Wait();
            }
            return(0);
        }
Beispiel #39
0
        public IContainer Build()
        {
            var builder = new ContainerBuilder();

            // pricing
            builder.RegisterType<PricePublisher>().As<IPricePublisher>().SingleInstance();
            builder.RegisterType<PriceFeedSimulator>().As<IPriceFeed>().SingleInstance();
            builder.RegisterType<PriceLastValueCache>().As<IPriceLastValueCache>().SingleInstance();
            builder.RegisterType<PricingHub>().SingleInstance();

            // reference data
            builder.RegisterType<CurrencyPairRepository>().As<ICurrencyPairRepository>().SingleInstance();
            builder.RegisterType<CurrencyPairUpdatePublisher>().As<ICurrencyPairUpdatePublisher>().SingleInstance();
            builder.RegisterType<ReferenceDataHub>().SingleInstance();

            // execution
            builder.RegisterType<ExecutionService>().As<IExecutionService>().SingleInstance();
            builder.RegisterType<ExecutionHub>().SingleInstance();

            // blotter
            builder.RegisterType<BlotterPublisher>().As<IBlotterPublisher>().SingleInstance();
            builder.RegisterType<TradeRepository>().As<ITradeRepository>().SingleInstance();
            builder.RegisterType<BlotterHub>().SingleInstance();

            builder.RegisterType<ContextHolder>().As<IContextHolder>().SingleInstance();

            return builder.Build();
        }
        protected void Application_Start()
        {
            Bootstrap.Log.Info("Application Start");

            Database.SetInitializer(new MigrateDatabaseToLatestVersion <BlochsTech.Website.Domain.Context.BlochsTechContext, BlochsTech.Website.Domain.Migrations.Configuration>());

            AreaRegistration.RegisterAllAreas();

            GlobalConfiguration.Configure(WebApiConfig.Register);

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Autofac Configuration
            var builder = new Autofac.ContainerBuilder();

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

            builder.RegisterModule(new DataAccessModule());
            builder.RegisterModule(new ServiceModule());
            builder.RegisterModule(new DomainModule());

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Beispiel #41
0
 static CentralDispatch()
 {
     var builder = new ContainerBuilder();
     BindKernel(builder);
     _container = builder.Build();
     InitilizeApp();
 }
Beispiel #42
0
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            var config     = GlobalConfiguration.Configuration;
            var assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray();
            //注册所有实现了 IDependency 接口的类型
            var baseType = typeof(IDependency);

            builder.RegisterAssemblyTypes(assemblies)
            .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
            .AsSelf().AsImplementedInterfaces()
            .InstancePerLifetimeScope();
            //注册MVC类型
            // builder.RegisterControllers(assemblies).PropertiesAutowired();
            //注册Api类型
            builder.RegisterApiControllers(assemblies);
            //builder.RegisterFilterProvider();
            builder.RegisterWebApiFilterProvider(config);
            var container = builder.Build();

            //注册api容器需要使用HttpConfiguration对象
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            //注册解析
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Beispiel #43
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>>>();
 }
Beispiel #44
0
        private void OwinStartup(IAppBuilder app)
        {
            HttpConfiguration   config = new HttpConfiguration();
            IDependencyResolver resolver;

#if true
            Unity.IUnityContainer uc = new Unity.UnityContainer();

            uc.RegisterInstance(typeof(IPlop), new Plop());
            resolver = new UnityResolver(uc);
#else
            Autofac.ContainerBuilder builder = new Autofac.ContainerBuilder();

            builder.RegisterApiControllers(typeof(WorkerRole).Assembly);
            builder.RegisterInstance(new Plop()).As <IPlop>();
            Autofac.IContainer container = builder.Build();

            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            resolver = new AutofacWebApiDependencyResolver(container);
#endif

            config.DependencyResolver = resolver;
            config.MapHttpAttributeRoutes();
            config.EnsureInitialized();

            app.UseWebApi(config);
        }
Beispiel #45
0
        static void Main(string[] args)
        {
            var env = new ApplicationEnvironment();
            var bootupConfigurationProvider = new BootupConfigurationProvider(env);

            Autofac.ContainerBuilder cb = new Autofac.ContainerBuilder();
            cb.RegisterInstance <IEnvironment>(env);
            cb.RegisterInstance(bootupConfigurationProvider).As <IBootupConfigurationProvider>();

            cb.RegisterModule <Teleware.Foundation.Core.Module>();
            cb.RegisterModule <Teleware.Foundation.Configuration.Module>();
            cb.RegisterModule <Teleware.Foundation.Diagnostics.Loggers.NLog.Module>();
            cb.RegisterModule <Teleware.Foundation.Data.Memory.Module>();
            //cb.RegisterModule<Teleware.Foundation.Data.EntityFramework.Module>();
            //cb.RegisterModule<Teleware.Foundation.Data.EntityFramework.Oracle.Module>();

            var container = cb.Build();

            using (var lt = container.BeginLifetimeScope())
            {
                while (true)
                {
                    var db = lt.Resolve <IOptions <DatabaseOptions> >();

                    Console.WriteLine(db.Value.ConnectionStrings.First().ToString());
                    Thread.Sleep(1000);
                }
            }
        }
        public async Task RouteAnKnownIntentToTheProperHandlerUsingAJsonConfigFile()
        {
            string intentName = "hijklmnop";
            string routeUri   = $"http://www.{intentName}.com";

            var cmdProcessor = new Mock <ICommandProcessor>(MockBehavior.Loose);

            var config = new ConfigurationBuilder()
                         .AddJsonFile("routes.json")
                         .Build();

            var containerBuilder = new Autofac.ContainerBuilder();

            containerBuilder.RegisterInstance <ICommandProcessor>(cmdProcessor.Object);
            containerBuilder.RegisterInstance <IConfiguration>(config);
            var serviceProvider = new AutofacServiceProvider(containerBuilder.Build());

            var intent  = new IntentBuilder().Random().AddName(intentName);
            var request = new UserRequestBuilder().Random().AddIntent(intent).Build();

            var target = new ConfigRouter.Engine(serviceProvider);
            var actual = await target.HandleRequestAsync(request);

            cmdProcessor.Verify(p => p.ProcessAsync(routeUri, It.IsAny <UserRequest>()), Times.Once);
        }
Beispiel #47
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);
        }
        public async Task RouteAnUnknownIntentToTheDefaultHandler()
        {
            string defaultRouteUri = $"http://{string.Empty.GetRandom()}";

            var cmdProcessor = new Mock <ICommandProcessor>(MockBehavior.Loose);

            var routes = new RouteCollectionBuilder(defaultRouteUri)
                         .Add(string.Empty.GetRandom(), string.Empty.GetRandom())
                         .Add(string.Empty.GetRandom(), string.Empty.GetRandom())
                         .Add(string.Empty.GetRandom(), string.Empty.GetRandom())
                         .Build().AsJsonString();
            var routeCollection = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("intentRoutes", routes)
            };
            var config = new ConfigurationBuilder().AddInMemoryCollection(routeCollection).Build();

            var containerBuilder = new Autofac.ContainerBuilder();

            containerBuilder.RegisterInstance <ICommandProcessor>(cmdProcessor.Object);
            containerBuilder.RegisterInstance <IConfiguration>(config);
            var serviceProvider = new AutofacServiceProvider(containerBuilder.Build());

            var request = new UserRequestBuilder().Random().Build();
            var target  = new ConfigRouter.Engine(serviceProvider);
            var actual  = await target.HandleRequestAsync(request);

            cmdProcessor.Verify(p => p.ProcessAsync(defaultRouteUri, It.IsAny <UserRequest>()), Times.Once);
        }
Beispiel #49
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();
            }
        }
Beispiel #50
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);


            //Autofac Configuration
            var builder = new Autofac.ContainerBuilder();

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



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

            builder.RegisterModule(new RepositoryModule());
            builder.RegisterModule(new ServiceModule());
            builder.RegisterModule(new EFModule());

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // Json default settings which only get parent entries not child
            //JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            //{
            //    Formatting = Newtonsoft.Json.Formatting.Indented,
            //    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            //};
        }
        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);
            }
        }
        public static void Register(Action <ContainerBuilder> action)
        {
            var builder = new Autofac.ContainerBuilder();

            builder.Register(x => SettingFactory.Create <PackSetting>()).As <PackSetting>().InstancePerLifetimeScope();

            builder.RegisterType <GitCommandHelper>().As <IGitCommandHelper>().InstancePerLifetimeScope();
            builder.RegisterType <PathService>().As <IPathService>().SingleInstance();
            builder.RegisterType <GitPackEngine>().As <IGitPackEngine>().InstancePerLifetimeScope();
            builder.RegisterType <FileAnalysisFactory>().As <IFileAnalysisFactory>().InstancePerLifetimeScope();
            builder.RegisterType <ProjectFilePreparer>().As <IChangedFilePreparer>().InstancePerLifetimeScope();

            builder.RegisterType <ScreenLogger>().As <ILogger>().SingleInstance();
            builder.RegisterType <VisualStudioProjectCompiler>().As <IVisualStudioProjectCompiler>().InstancePerLifetimeScope();
            //builder.RegisterType<FakeCompilier>().As<IVisualStudioProjectCompiler>().InstancePerLifetimeScope();
            builder.RegisterType <FilePackService>().As <IFilePackService>().InstancePerLifetimeScope();

            builder.RegisterType <BuildServiceFactory>().As <IBuildServiceFactory>().InstancePerLifetimeScope();
            builder.RegisterType <ProjectParserServiceFactory>().As <IProjectParserServiceFactory>().InstancePerLifetimeScope();
            builder.RegisterType <VisualStudioProjectFinder>().As <IProjectFinder>().InstancePerLifetimeScope();
            builder.RegisterType <ProjectFilter>().As <IProjectFilter>().SingleInstance();
            builder.RegisterType <PackageCompressService>().As <IPackageCompressService>().InstancePerLifetimeScope();
            builder.RegisterType <ProjectDiffer>().As <IProjectDiffer>().InstancePerLifetimeScope();
            builder.RegisterType <VisualStudioSolutionFinder>().As <ISolutionFinder>().InstancePerLifetimeScope();
            builder.RegisterType <VisualStudioSolutionParser>().As <ISolutionParser>().InstancePerLifetimeScope();
            builder.RegisterType <NugetPackageManager>().As <INugetPackageManager>().InstancePerLifetimeScope();

            action(builder);

            IContainer iocContainer = builder.Build();

            ContainerManager.SetContainer(iocContainer);
        }
Beispiel #53
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();
        }
        private static async Task Main(string[] args)
        {
            var builder = new Autofac.ContainerBuilder();

            builder.RegisterType <ProcessUserSessionActor>();
            var container = builder.Build();

            using var system = ActorSystem.Create("MySystem");
            system.UseAutofac(container);

            var brain = system.ActorOf <SessionManager>();

            var messages = new ProcessUserSession[100];

            messages.AsSpan().Fill(new ProcessUserSession());

            var random = new Random();

            for (var i = 0; i < 500; i++)
            {
                var message = messages[random.Next(0, messages.Length)];
                brain.Tell(message);
            }

            // wait for all message processing
            await Task.Delay(4000);

            Console.WriteLine("DONE -- Press any key to terminate.");
            Console.ReadKey();
        }
Beispiel #55
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();
        }
Beispiel #56
0
        public MainWindow()
        {
            InitializeComponent();

            // Init Autofac.WCF container
            builder = new ContainerBuilder();
            // Register the channel factory for the service. Make it
            // SingleInstance since you don't need a new one each time.
            builder
              .Register(c => new ChannelFactory<WcfProxies.Proxies.External.IBlogPostService>(
                new WSHttpBinding(),
                new EndpointAddress("http://localhost:9002/BlogPostService")))
              .SingleInstance();
            // Register the service interface using a lambda that creates
            // a channel from the factory. Include the UseWcfSafeRelease()
            // helper to handle proper disposal.
            builder
              .Register(c => c.Resolve<ChannelFactory<WcfProxies.Proxies.External.IBlogPostService>>()
              .CreateChannel())
              .As<WcfProxies.Proxies.External.IBlogPostService>()
              .UseWcfSafeRelease();

            // You can also register other dependencies.
            builder.RegisterType<WcfProxies.Proxies.External.BlogPostClientExt>();

            container = builder.Build();
        }
		private void RegisterContainer() {
			var builder = new ContainerBuilder();
			builder.RegisterControllers(Assembly.GetExecutingAssembly());
			_pluginServicee.Startup(builder);
			_container = builder.Build();
			DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));
		}
        private static void SetIocContainer()
        {
            //Implement Autofac

            var configuration = GlobalConfiguration.Configuration;
            var builder = new ContainerBuilder();

            // Register MVC controllers using assembly scanning.
            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            // Register MVC controller and API controller dependencies per request.
            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerDependency();
            builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerLifetimeScope();

            // Register service
            builder.RegisterAssemblyTypes(typeof(ProfileService).Assembly)
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces().InstancePerDependency();

            // Register repository
            builder.RegisterAssemblyTypes(typeof(ProfileRepository).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces().InstancePerDependency();

            var container = builder.Build();

            //for MVC Controller Set the dependency resolver implementation.
            var resolverMvc = new AutofacDependencyResolver(container);
            System.Web.Mvc.DependencyResolver.SetResolver(resolverMvc);
        }
Beispiel #59
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"));
        }
Beispiel #60
0
        public static void RegistAll()
        {
            var iocBuilder = new Autofac.ContainerBuilder();

            iocBuilder.RegisterControllers(Assembly.GetExecutingAssembly());
            iocBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            //Type baseType = typeof(IH2FBase);
            var iInterfaces = Assembly.Load("H2F.TEST.Interface");
            var implement   = Assembly.Load("H2F.TEST.Implement");

            iocBuilder.RegisterAssemblyTypes(iInterfaces, implement).AsImplementedInterfaces();

            iocBuilder.RegisterType <Student>().As <IPerson>();
            iocBuilder.RegisterType <Worker>().Keyed <IPerson>(PersonType.Worker);

            iocBuilder.RegisterType <Student>().Keyed <IPerson>(PersonType.Student);


            iocBuilder.RegisterType <Log4net>().As <ILogger>();
            var config = GlobalConfiguration.Configuration;

            iocBuilder.RegisterWebApiFilterProvider(config);
            IContainer iocContainer = iocBuilder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(iocContainer);
            System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(iocContainer));

            IocContainerManager.SetContanier(iocContainer);
        }