public void SetUp() { var builder = new ContainerBuilder(); builder.RegisterModule<CoreModule>(); builder.RegisterModule<LuaModule>(); this.container = builder.Build(); }
public static Autofac.IContainer Strap() { OnProgressChanged(0, @"Start bootstraping..."); if (_builder.IsNull()) { _builder = new ContainerBuilder(); _builder.RegisterModule(new InfrastructureModule(25000, new[] { @"Server=127.0.0.1;Database=macsauto2;User Id=root;Password=root", @"Server=codebrosdb.c7n7mt4zucyl.ap-southeast-1.rds.amazonaws.com;User Id=codebros;Password=codebros" })); _builder.RegisterModule(new InfrastructureCrosscuttingModule()); _builder.RegisterModule(new PresentationModule()); _container = _container ?? _builder.Build(); _builder = new ContainerBuilder(); _builder.RegisterInstance(_container).As<Autofac.IContainer>(); _builder.Update(_container); _strapped = true; } OnProgressChanged(20, @"Done registering modules.."); return _container; }
private static IContainer RegisterServices(ContainerBuilder builder) { builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // EF EIContext builder.RegisterType<EIContext>() .As<DbContext>() .InstancePerRequest(); builder.RegisterType<DbFactory>() .As<IDbFactory>() .InstancePerRequest(); builder.RegisterType<UnitOfWork>() .As<IUnitOfWork>() .InstancePerRequest(); builder.RegisterGeneric(typeof(EntityBaseRepository<>)) .As(typeof(IEntityBaseRepository<>)) .InstancePerRequest(); // Services builder.RegisterType<EncryptionService>() .As<IEncryptionService>() .InstancePerRequest(); builder.RegisterType<MembershipService>() .As<IMembershipService>() .InstancePerRequest(); Container = builder.Build(); return Container; }
public ConnectionController(IContainer c) { model = c.Resolve<Model>(); mserver = c.Resolve<MulticastServerService>(); peerFinder = c.Resolve<LANPeerFinderService>(); setupLocalNetwork(); }
public void SetUp() { builder = new ContainerBuilder(); builder.RegisterType<TestConventions>().As<IConventions>(); container = builder.RegisterAsEasyNetQContainerFactory(); bus = new MockBuilder().Bus; }
public static void RegisterControllers(params Assembly[] assemblies) { builder.RegisterControllers(assemblies); builder.RegisterAssemblyTypes(typeof(IRepository).Assembly) .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces().InstancePerLifetimeScope(); container = builder.Build(); }
public static void BootStrap() { _builder = new ContainerBuilder(); Container = _builder.Build(); _builder = new ContainerBuilder(); BindFrameworkObjects(); BindBusinessObjects(); _builder.Update(Container); }
void App_Startup(object sender, StartupEventArgs e) { var containerBuilder = new ContainerBuilder(); // register components modules containerBuilder.RegisterModule(new ProxiesModule()); containerBuilder.RegisterModule(new ViewModelModule()); _container = containerBuilder.Build(); }
private void AutoFacBenchmark(IContainer container) { using (container.BeginLifetimeScope()) { Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Continuing with AutoFac tests"); Stopwatch timer; TimeSpan elapsed5; timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.Resolve<ITestClass>(); } timer.Stop(); elapsed5 = timer.Elapsed; Singleton = new KeyValuePair<TimeSpan, TimeSpan>(Singleton.Key, elapsed5); Console.WriteLine("{0} instances created with singleton resolves in {1} ms", Iterations, elapsed5.TotalMilliseconds); timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.Resolve<ITestClass2>(); } timer.Stop(); elapsed5 = timer.Elapsed; Transient = new KeyValuePair<TimeSpan, TimeSpan>(Transient.Key, elapsed5); Console.WriteLine("{0} instances created with transient resolves in {1} ms", Iterations, elapsed5.TotalMilliseconds); timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.ResolveNamed<ITestClass>(ServiceName); } timer.Stop(); elapsed5 = timer.Elapsed; Console.WriteLine("{0} instances created with transient resolves by name {1} ms", Iterations, elapsed5.TotalMilliseconds); timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.Resolve<ITestClass3>(); if (instance.TClass == null) Console.WriteLine("Injection failed"); } timer.Stop(); elapsed5 = timer.Elapsed; TransientWithInjection = new KeyValuePair<TimeSpan, TimeSpan>(TransientWithInjection.Key, elapsed5); Console.WriteLine("{0} instances created with transient resolves with injection in {1} ms", Iterations, elapsed5.TotalMilliseconds); } }
/// <summary> /// Initializes a new instance of <see cref="CurveDisplay"/>. /// </summary> public CurveDisplay() { InitializeComponent(); _container = new ContainerFactory(this).Build(); _printingRedrawRequest = _container.Resolve<IPrintingRedrawRequest>(); TimeDoublePlottingSystem = _container.Resolve<TimeDoublePlottingSystem>(); _curveDrawingSurfaceControl = (FrameworkElement)_container.Resolve<ICurveDrawingSurface>(); SurfaceViewbox.Child = _curveDrawingSurfaceControl; }
void CreateContainer() { var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterAssemblyModules(typeof(AppBootstrapper).Assembly); containerBuilder.RegisterExternalModules(); container = containerBuilder.Build(); // We reregister the container within itself. // This is bad and we should feel bad about it. containerBuilder = new ContainerBuilder(); containerBuilder.RegisterInstance(container).SingleInstance(); containerBuilder.Update(container); }
public int Run() { var builder = CreateContainerBuilder(); SetupLogging(builder); container = builder.Build(); var cancellationToken = CreateCancellationToken(); Task.WaitAll(Run(cancellationToken)); return 0; }
public Searcher() { Autofac.ContainerBuilder cb = new Autofac.ContainerBuilder(); /* cb.Register(c => new ClientServer(this)); cb.RegisterType<ClientServer>().As<ICommunication>(); cb.RegisterInstance(new ClientServer(this)); */ cb.Register(c => new EntityHandler()); cb.RegisterType<EntityHandler>().As<IDataBaseSearcher>(); cb.RegisterInstance(new EntityHandler()); Container = cb.Build(); // Communication = Container.Resolve<ClientServer>(); DataBase = Container.Resolve<EntityHandler>(); }
public void Configure() { ContainerBuilder builder = new ContainerBuilder(); OnConfigure(builder); if (this.myContainer == null) { this.myContainer = builder.Build(); } else { builder.Update(this.myContainer); } //This tells the MVC application to use myContainer as its dependency resolver DependencyResolver.SetResolver(new AutofacDependencyResolver(this.myContainer)); }
public ApplicationCore(IContainer c) { container = c; model = container.Resolve<Model>(); logService = container.Resolve<LogService>(); connectionController = c.Resolve<ConnectionController>(); //Don't send two request went doing a post.. ServicePointManager.Expect100Continue = false; //Don't limit connections to a single node - 100 I think is the upper limit. ServicePointManager.DefaultConnectionLimit = 100; //System.Net.ServicePointManager.MaxServicePointIdleTime = 20000000; updateChecker = container.Resolve<UpdateCheckerService>(); interfaceController = container.Resolve<InterfaceController>(); overlordManagerService = container.Resolve<OverlordManagerService>(); singleInstanceService = new SingleInstanceService("FAP"); registerProtocolService = new RegisterProtocolService(); }
public void Configure() { ContainerBuilder builder = new ContainerBuilder(); builder = OnConfigure(builder); builder.RegisterControllers(Assembly.GetExecutingAssembly()); if (this.myContainer == null) { this.myContainer = builder.Build(); } else { builder.Update(this.myContainer); } DependencyResolver.SetResolver(new AutofacDependencyResolver(this.myContainer)); }
private static Autofac.IContainer RegisterServices(ContainerBuilder builder) { //Register your Web API controllers. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterType <ProductService>() .As <IProductService>() .InstancePerRequest(); builder.RegisterType(typeof(DataAccessHelper)) .As(typeof(IDataAccessHelper)) .InstancePerRequest(); //Set the dependency resolver to be Autofac. Container = builder.Build(); return(Container); }
private IServiceProvider RegisterAutofac(IServiceCollection services) { var builder = new ContainerBuilder(); //SingleService Injection //builder.RegisterType<ArticleSvc>().As<IArticleSvc>().InstancePerLifetimeScope(); //builder.RegisterType<CommentSvc>().As<ICommentSvc>().InstancePerLifetimeScope(); //Attribute&Filter Injection builder.RegisterType <CustomerExceptionFilter>();/*NLogFilterAttribute*/ //Module Injection builder.RegisterModule <UtilModule>(); builder.RegisterModule <DomainServiceModule>(); builder.RegisterModule <ServiceModule>(); builder.Populate(services); ApplicationContainer = builder.Build(); return(new AutofacServiceProvider(ApplicationContainer)); }
public static void InitializeContainer(AppConfiguration configuration, Action <ContainerBuilder> configurator = null) { logger.Info("Initializating app container"); var builder = new ContainerBuilder(); //https://github.com/jbogard/MediatR/issues/128 builder.RegisterSource(new ScopedContravariantRegistrationSource()); builder.RegisterModule(new ServicesModule()); builder.RegisterModule(new NHibernateModule(configuration.ConnectionString, configuration.RecreateDatabase, false, configuration.NHibernateTimeout)); configurator?.Invoke(builder); container = builder.Build(); }
//------------------------------------------DI Container Build------------------------------------------// private void CreateAutofacContainer() { var builder = new Autofac.ContainerBuilder(); // Allow the composite application plug-in modules // to register services with container. _application.RegisterComponents(builder); // Register additional services, RegisterAppContainerAsService(builder); RegisterPluginModuleServices(builder); RegisterHostProvidedServices(builder); // Register logging and configuration. RegisterLogging(builder); RegisterConfigSettings(builder); _container = builder.Build(); }
public void ConfigAutofac(IAppBuilder app) { //khởi tạo builder để register các DI ContainerBuilder builder = new ContainerBuilder(); //register cho controller //InstancePerRequest tức là mỗi session(phiên làm việc) thì nó sẽ tự động khởi tạo builder.RegisterControllers(Assembly.GetExecutingAssembly()); builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerRequest(); builder.RegisterType <DbFactory>().As <IDbFactory>().InstancePerRequest(); //register dbcontext builder.RegisterType <TeduShopDbContext>().AsSelf().InstancePerRequest(); #region Add DI // services builder.RegisterAssemblyTypes(typeof(PostCategoryService).Assembly) .Where(x => x.Name.EndsWith("Service")) .AsImplementedInterfaces() .InstancePerRequest(); builder.RegisterAssemblyTypes(typeof(ErrorService).Assembly) .Where(x => x.Name.EndsWith("Service")) .AsImplementedInterfaces() .InstancePerRequest(); //repository builder.RegisterAssemblyTypes(typeof(PostCategoryRepository).Assembly) .Where(x => x.Name.EndsWith("Repository")) .AsImplementedInterfaces() .InstancePerRequest(); builder.RegisterAssemblyTypes(typeof(ErrorRepository).Assembly) .Where(x => x.Name.EndsWith("Repository")) .AsImplementedInterfaces() .InstancePerRequest(); //dùng autofac tạo ra container(thùng chứa) để chứa các register trên Autofac.IContainer container = builder.Build(); //thay thế auto của autofac thành các register DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //config cho cả web api GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); #endregion }
private static Autofac.IContainer RegisterServices(ContainerBuilder builder) { builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterType <AdvertRepository>() .As <IRepository <AdvertEntity> >() .InstancePerRequest(); builder.RegisterType <AdvertAddressDetailsRepository>() .As <IRepository <AdvertAddressDetailsEntity> >() .InstancePerRequest(); builder.RegisterType <TagRepository>() .As <IRepository <TagEntity> >() .InstancePerRequest(); builder.RegisterType <AdvertImageRepository>() .As <IRepository <AdvertImageEntity> >() .InstancePerRequest(); builder.RegisterType <AccountRepository>() .As <IRepository <AccountEntity> >() .InstancePerRequest(); builder.RegisterType <AccountPhoneNumberRepository>() .As <IRepository <AccountPhoneNumberEntity> >() .InstancePerRequest(); builder.RegisterType <ImageUploadService>() .As <IImageUploadService>() .InstancePerRequest(); builder.RegisterType <AdvertImageService>() .As <IAdvertImageService>() .InstancePerRequest(); builder.RegisterType <AccountService>() .As <IAccountService>() .InstancePerRequest(); builder.RegisterType <AdvertService>() .As <IAdvertService>() .InstancePerRequest(); builder.RegisterType <TagService>() .As <ITagService>() .InstancePerRequest(); Container = builder.Build(); return(Container); }
private void ConfigAutofac(IAppBuilder app) { var builder = new ContainerBuilder(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); // Register your Web API controllers. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //Register WebApi Controllers builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerRequest(); builder.RegisterType <DbFactory>().As <IDbFactory>().InstancePerRequest(); builder.RegisterType <TrainingShopDbContext>().AsSelf().InstancePerRequest(); //Asp.net Identity builder.RegisterType <ApplicationUserStore>().As <IUserStore <ApplicationUser> >().InstancePerRequest(); builder.RegisterType <ApplicationUserManager>().AsSelf().InstancePerRequest(); builder.RegisterType <ApplicationSignInManager>().AsSelf().InstancePerRequest(); builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest(); builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest(); // Repositories builder.RegisterAssemblyTypes(typeof(PostCategoryRepository).Assembly) .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces().InstancePerRequest(); builder.RegisterAssemblyTypes(typeof(ProductCategoryRepository).Assembly) .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces().InstancePerRequest(); // Services builder.RegisterAssemblyTypes(typeof(PostCategoryService).Assembly) .Where(t => t.Name.EndsWith("Service")) .AsImplementedInterfaces().InstancePerRequest(); builder.RegisterAssemblyTypes(typeof(ProductCategoryService).Assembly) .Where(t => t.Name.EndsWith("Service")) .AsImplementedInterfaces().InstancePerRequest(); Autofac.IContainer container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container); //Set the WebApi DependencyResolver }
public IServiceProvider ConfigureServices(IServiceCollection services) { // Services, etc. var builder = new ContainerBuilder(); // Load asp.net core services services.AddRouting(); services.AddMvc().AddFluentValidation(); // Standard extensions new ServiceExtensions().AddCors(services); // Convert to autofac builder.Populate(services); _container = builder.Build(); // Bind autofac as service provider return(new AutofacServiceProvider(_container)); }
private void ConfigAutofac(IAppBuilder app) { var builder = new ContainerBuilder(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerRequest(); builder.RegisterType <DbFactory>().As <IDbFactory>().InstancePerRequest(); builder.RegisterType <EcommerceDbContext>().AsSelf().InstancePerRequest(); builder.RegisterAssemblyTypes(typeof(PostCategoryRepository).Assembly) .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces() .InstancePerRequest(); builder.RegisterAssemblyTypes(typeof(PostCategoryService).Assembly) .Where(t => t.Name.EndsWith("Service")) .AsImplementedInterfaces() .InstancePerRequest(); Autofac.IContainer container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
public async Task MainAsync() { ///////////initialize autofac SettingsTripleZeroBot settingsTripleZeroBot = null; autoFacContainer = AutofacConfig.ConfigureContainer(); using (var scope = autoFacContainer.BeginLifetimeScope()) { applicationSettings = scope.Resolve <ApplicationSettings>(); commands = scope.Resolve <CommandService>(); client = scope.Resolve <DiscordSocketClient>(); logo = scope.Resolve <Logo>(); //memoryCache = scope.Resolve<MemoryCache>(); settingsTripleZeroBot = applicationSettings.GetTripleZeroBotSettings(); await InstallCommands(); await client.LoginAsync(TokenType.Bot, settingsTripleZeroBot.DiscordSettings.Token); await client.StartAsync(); await client.SetGameAsync(string.Format("{0}help", settingsTripleZeroBot.DiscordSettings.Prefix)); } //client.MessageReceived += MessageReceived; while (client.ConnectionState != ConnectionState.Connected) { Consoler.WriteLineInColor(string.Format("Still not connected... {0}", DateTime.Now), ConsoleColor.Yellow); await Task.Delay(2000); } logo.ConsolePrintLogo(); //prints application name,version etc //await TestCharAliasesDelete(); //await TestDelete(); //await TestGuildPlayers("41st"); //await TestPlayerReport("tsitas_66"); //await TestGuildModule("41s", "gk"); //await TestCharacterModule("tsitas_66", "cls"); await client.GetUser("TSiTaS", "1984").SendMessageAsync(logo.GetLogo()); await Task.Delay(-1); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddOptions(); services.ConfigureCors(); services.ConfigureIISIntegration(); services.AddControllers(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddDbContext <StudentContext>(options => options.UseSqlServer(Configuration.GetConnectionString("sqlConnection"))); services.AddAutoMapper(typeof(MappingProfile)); // Create a Autofac container builder var builder = new ContainerBuilder(); // Read service collection to Autofac builder.Populate(services); // build the Autofac container ApplicationContainer = builder.Build(); ConfigureDependencyInjection(services); }
/// <summary> /// 初始化Opc服务 /// </summary> private IOpcClient OpcFinder(string opcName) { ContainerBuilder builder = new ContainerBuilder(); Type opcType = null; Type baseType = typeof(IOpcClient); // 获取所有OPC相关类库的程序集 Assembly[] assemblies = GetOpcAssemblies(); foreach (Assembly assembly in assemblies) { try { // opcType = assembly.GetTypes() //.Where(type => type.Name == opcName && baseType.IsAssignableFrom(type) && !type.IsAbstract).FirstOrDefault(); opcType = assembly.GetType(opcName); if (opcType != null) { builder.RegisterType(opcType) .Named <IOpcClient>(opcName) .SingleInstance(); break; } } catch (Exception ex) { AddMsgToList(ex.ToString()); } } //Autofac.IContainer container = builder.Build(); //IOpcClient opcClient = container.ResolveNamed<IOpcClient>(opcName); IOpcClient opcClient; //构建容器来完成注册并准备对象解析。 Autofac.IContainer container = builder.Build(); // 现在您可以使用Autofac解决服务问题。例如,这一行将执行注册到IConfigReader服务的lambda表达式。 using (var scope = container.BeginLifetimeScope()) { opcClient = container.ResolveNamed <IOpcClient>(opcName); } return(opcClient); }
protected override void Configure() { // set up NLog LogManager.GetLog = t => new NLogAdaptor(); // Autofac builder var builder = new ContainerBuilder(); // register the shell builder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray()) .Where(type => type.Name.Equals("ShellViewModel")) .AsSelf() .SingleInstance(); // register view models builder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray()) .Where(type => type.Name.EndsWith("ViewModel")) // must be in a namespace ending with ViewModels .Where(type => !(string.IsNullOrWhiteSpace(type.Namespace)) && type.Namespace.EndsWith("ViewModels")) // must implement INotifyPropertyChanged (deriving from PropertyChangedBase will statisfy this) .Where(type => type.GetInterface(typeof(INotifyPropertyChanged).Name) != null) // registered as self .AsSelf() .InstancePerDependency(); // register views builder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray()) // must be a type that ends with View .Where(type => type.Name.EndsWith("View")) .AsSelf() .InstancePerDependency(); // register the single window manager for this container builder.Register <IWindowManager>(c => new WindowManager()) .As <IWindowManager>() .InstancePerLifetimeScope(); // register the single event aggregator for this container builder.Register <IEventAggregator>(c => new EventAggregator()).InstancePerLifetimeScope(); _container = builder.Build(); }
protected virtual void CreateContainer() { var builder = new ContainerBuilder(); builder.RegisterInstance(m_Host.Extension).ExternallyOwned(); builder.RegisterInstance(m_Host.Extension.Application).ExternallyOwned(); builder.RegisterInstance(m_Host.Extension.Logger); builder.RegisterType <AppLogger>() .As <IXLogger>(); builder.RegisterType <MacroEntryPointsExtractor>() .As <IMacroEntryPointsExtractor>(); builder.RegisterType <MacroRunner>() .As <IMacroRunner>(); builder.RegisterType <ToolbarConfigurationProvider>() .As <IToolbarConfigurationProvider>(); builder.RegisterType <SettingsProvider>() .As <ISettingsProvider>(); builder.RegisterType <CommandManagerVM>() .SingleInstance(); builder.RegisterType <CommandsManager>() .As <ICommandsManager>().SingleInstance(); builder.RegisterType <TriggersManager>() .As <ITriggersManager>().SingleInstance(); builder.RegisterType <UserSettingsService>(); builder.RegisterFromServiceProvider <IMacroRunnerExService>(m_Host.Services); builder.RegisterFromServiceProvider <IMessageService>(m_Host.Services); builder.RegisterFromServiceProvider <IMacroFileFilterProvider>(m_Host.Services); builder.RegisterInstance(m_IconsProviders.ToArray()); m_Container = builder.Build(); }
/// <summary> /// </summary> /// <returns></returns> public static Configuration UseAutofacContainer(this Configuration configuration, IContainer container = null, string configFile = "autofac.xml") { if (IoCFactory.IsInit()) { return(configuration); } var builder = new ContainerBuilder(); if (container == null) { // Add the configuration to the ConfigurationBuilder. var config = new ConfigurationBuilder(); // config.AddJsonFile comes from Microsoft.Extensions.Configuration.Json // config.AddXmlFile comes from Microsoft.Extensions.Configuration.Xml var fi = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configFile)); if (fi.Exists) { if (fi.Extension.Equals(".xml", StringComparison.OrdinalIgnoreCase)) { config.AddXmlFile(configFile); } else if (fi.Extension.Equals(".json", StringComparison.OrdinalIgnoreCase)) { config.AddJsonFile(configFile); } // Register the ConfigurationModule with Autofac. var module = new ConfigurationModule(config.Build()); builder.RegisterModule(module); } builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()); container = builder.Build(); } else { builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()); builder.Update(container); } IoCFactory.SetContainer(new ObjectContainer(container)); return(configuration); }
public MainForm() { InitializeComponent(); var cb = new ContainerBuilder(); cb.RegisterModule <DiMainModule>(); IContainer container = cb.Build(); _importer = container.Resolve <CityEventFromFacebookImporter>(); _retriever = container.Resolve <FacebookEventRetriever>(); _fb = container.Resolve <FacebookClient>(); _fbLoginUri = _fb.GetLoginUrl(new { client_id = Settings.Default.AppId, redirect_uri = "https://www.facebook.com/connect/login_success.html", response_type = "token", scope = "rsvp_event,user_events,publish_actions" }); _eventFormat = container.Resolve <FacebookEventFormat>(); InitializeChromium(_fbLoginUri.AbsoluteUri); try { using (var f = new StreamReader(EventsCSV)) { _events.AddRange( container.Resolve <CsvStorage>().ReadAll(f).Select( x => { FixDescription(x); return(x); })); } } catch (FileNotFoundException) { } if (Settings.Default.SearchQueries != null) { QueryBox.Items.AddRange(Settings.Default.SearchQueries.Cast <object>().ToArray()); } }
public static AutofacServiceProvider Configure(this IServiceCollection services, string connectionString, IConfigurationRoot configuration) { services.AddDbContext <MyContext>(options => options.UseSqlServer(connectionString)); //FluentValidation后台验证 services.AddTransient(typeof(IBaseRepository <>), typeof(BaseRepository <>)); //通过反射进行依赖注入不能为空 services.RegisterAssembly("ProjectCore.Domain.Repository.Interfaces", "ProjectCore.Infrastructure.Repository"); services.RegisterAssembly("ProjectCore.Application"); services.RegisterAssembly("ProjectCore.Domain.DomainService", "ProjectCore.Infrastructure.DomainService"); //Autofac依赖注入 Class的后面名字必须一致才能注入 var builder = new ContainerBuilder(); builder.Populate(services); var module = new ConfigurationModule(configuration); builder.RegisterModule(module); Container = builder.Build(); return(new AutofacServiceProvider(Container)); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { try { services.AddSwaggerGen(cfg => { cfg.SwaggerDoc("v1", new Info { Title = "TunZhouAPI", Version = "v1" }); var xmlFileName = "TunZhou.API.xml"; var xmlFilePath = Path.Combine(Environment.ContentRootPath, xmlFileName); if (File.Exists(xmlFilePath)) { cfg.IncludeXmlComments(xmlFilePath); } }); } catch (Exception ex) { throw ex; } services.AddMemoryCache();//注册缓存服务 //services.AddMvc(config => //{ // config.Filters.Add(new SignVerificationFilter()); //});//注册过滤器,当注册后所有action都将公用该过滤器 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); var builder = new ContainerBuilder(); //注册Service中的对象,Service中的类要以Service结尾,否则注册失败 builder.RegisterAssemblyTypes(GetAssemblyByName("TunZhou.Services")).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces(); //注册Repository中的对象,Repository中的类要以Repository结尾,否则注册失败 builder.RegisterAssemblyTypes(GetAssemblyByName("TunZhou.Repositories")).Where(a => a.Name.EndsWith("Repository")).AsImplementedInterfaces(); builder.RegisterType <RedisService>().As <IRedisService>().SingleInstance(); builder.Populate(services); ApplicationContainer = builder.Build(); return(new AutofacServiceProvider(ApplicationContainer)); }
private void ConfigAutofac(IAppBuilder app) { var builder = new ContainerBuilder(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerRequest(); builder.RegisterType <DbFactory>().As <IDbFactory>().InstancePerRequest(); builder.RegisterType <ContextConnection>().AsSelf().InstancePerRequest(); //Asp.net Identity builder.RegisterType <ApplicationUserStore>().As <IUserStore <ApplicationUser> >().InstancePerRequest(); builder.RegisterType <ApplicationUserManager>().AsSelf().InstancePerRequest(); builder.RegisterType <ApplicationSignInManager>().AsSelf().InstancePerRequest(); builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest(); builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest(); // Repositories builder.RegisterAssemblyTypes(typeof(ErrorRepository).Assembly) .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces().InstancePerRequest(); // Repositories builder.RegisterAssemblyTypes(typeof(RoleRepository).Assembly) .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces().InstancePerRequest(); // Services builder.RegisterAssemblyTypes(typeof(ErrorService).Assembly) .Where(t => t.Name.EndsWith("Service")) .AsImplementedInterfaces().InstancePerRequest(); // Services builder.RegisterAssemblyTypes(typeof(RoleService).Assembly) .Where(t => t.Name.EndsWith("Service")) .AsImplementedInterfaces().InstancePerRequest(); Autofac.IContainer container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
public static IContainer InitForTest(IServiceCollection services) { var builder = new ContainerBuilder(); //注册数据库基础操作和工作单元 services.AddScoped(typeof(IRepository <>), typeof(BaseRepository <>)); services.AddScoped(typeof(IUnitWork), typeof(UnitWork)); //如果当前项目是webapi,则必须是本地,否则会引起死循环 if (Assembly.GetEntryAssembly().FullName.Contains("OpenAuth.WebApi")) { services.AddScoped(typeof(IAuth), typeof(LocalAuth)); } else //如果是MVC或者单元测试,则可以根据情况调整,默认是本地授权,无需OpenAuth.WebApi、Identity { services.AddScoped(typeof(IAuth), typeof(LocalAuth)); //如果想使用WebApi SSO授权,请使用下面这种方式 //services.AddScoped(typeof(IAuth), typeof(ApiAuth)); } //注册app层 builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()); //防止单元测试时已经注入 if (services.All(u => u.ServiceType != typeof(ICacheContext))) { services.AddScoped(typeof(ICacheContext), typeof(CacheContext)); } if (services.All(u => u.ServiceType != typeof(IHttpContextAccessor))) { services.AddScoped(typeof(IHttpContextAccessor), typeof(HttpContextAccessor)); } builder.RegisterModule(new QuartzAutofacFactoryModule()); builder.Populate(services); _container = builder.Build(); return(_container); }
public MainService() { tasks = new List <Task>(); cancelToken = new CancellationTokenSource(); //Autofac初始化 container = LogNewHelper.BuildAutofacContainer(); //rabbitMQ初始化 var config = System.Configuration.ConfigurationManager.GetSection("rabbitMQ") as RabbitMQConfigurationSection; rabbitMQProxy = new RabbitMQWrapper(new RabbitMQConfig { Host = config.HostName, VirtualHost = config.VHost, HeartBeat = 60, AutomaticRecoveryEnabled = true, UserName = config.UserName, Password = config.Password }); }
private static void SetAutofacContainer() { var builder = new ContainerBuilder(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerRequest(); builder.RegisterType <DbFactory>().As <IDbFactory>().InstancePerRequest(); // Initialize Services // System // Repositories builder.RegisterAssemblyTypes(typeof(CategoryRepository).Assembly).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces().InstancePerRequest(); // Services builder.RegisterAssemblyTypes(typeof(CategoryService).Assembly).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerRequest(); builder.RegisterAssemblyTypes(typeof(ZUSRService).Assembly).Where(t => t.Name.EndsWith("Service")).InstancePerRequest(); Autofac.IContainer container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
private static void InitRegisterDependency() { try { var builder = new ContainerBuilder(); builder.Register <IDbContext>(c => new PrjObjectContext()).InstancePerLifetimeScope(); //repositories builder.RegisterGeneric(typeof(EfRepository <>)).As(typeof(IRepository <>)).InstancePerLifetimeScope(); builder.RegisterType <Log4netService>().As <ILogService>().InstancePerLifetimeScope(); builder.RegisterType <ProductService>().As <IProductService>().InstancePerLifetimeScope(); builder.RegisterType <CategoryService>().As <ICategoryService>().InstancePerLifetimeScope(); _container = builder.Build(); }catch (Exception) { } }
private static Autofac.IContainer RegisterServices(ContainerBuilder builder) { builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // EF HomeCinemaContext // Services //builder.RegisterType<EncryptionService>() // .As<IEncryptionService>() // .InstancePerRequest(); builder.RegisterType<MembershipService>() .As<IMembershipService>() .InstancePerRequest(); Container = builder.Build(); return Container; }
private static IServiceProvider BuildDependencyInjectionProvider(IConfigurationRoot config, IServiceCollection services) { //services.AddSingleton(c => GetApplicationInsightsTelemetryClient(config[Constants.ConfigurationKey.AppSettings.ApplicationInsights.InstrumentationKey])); var module = new ConfigurationModule(config); // Now register our services with Autofac container. var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterModule(module); containerBuilder.RegisterModule(new CoreModule()); //NOTE: UseCaseの追加が必要 containerBuilder.RegisterModule(new InfrastructureModule()); //NOTE: Repositoryの追加が必要 containerBuilder.RegisterModule(new ServerLogger.Infra.InfrastructureModule()); //NOTE: Repositoryの追加が必要 // Presenters containerBuilder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Presenter")).SingleInstance(); containerBuilder.Populate(services); Autofac.IContainer container = containerBuilder.Build(); // Create the IServiceProvider based on the container. return(new AutofacServiceProvider(container)); }
public void TestFixtureSetUp() { this.builder = new ContainerBuilder(); this.builder.RegisterGeneric(typeof(BindingList<>)).UsingConstructor(new Type[] { }).As(typeof(IList<>)). InstancePerDependency(); this.builder.RegisterModule<BaseEditorsAutofacModule>(); this.builder.RegisterModule<MarmaladeEditorsAutofacModule>(); this.builder.RegisterModule<MarmaladeAutofacModule>(); this.builder.RegisterModule<MarmaladeTextFilesAutofacModule>(); this.builder.RegisterModule<MarmaladeBinaryFilesAutofacModule>(); this.builder.RegisterModule<MarmaladeTextureFilesAutofacModule>(); this.builder.RegisterType<ToeGraphicsContext>().As<ToeGraphicsContext>().SingleInstance(); this.builder.RegisterType<ResourceErrorHandler>().As<IResourceErrorHandler>().SingleInstance(); this.builder.RegisterType<ResourceManager>().As<IResourceManager>().SingleInstance(); this.builder.RegisterType<ResourceFile>().As<IResourceFile>().InstancePerDependency(); this.builder.RegisterType<ResourceFileItem>().As<IResourceFileItem>().InstancePerDependency(); this.container = this.builder.Build(); var l = this.container.Resolve<IList<int>>(); }
protected override void Configure() { var builder = new ContainerBuilder(); builder.RegisterType <TickerFactory>().As <ITickerFactory>(); builder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray()) .Where(type => type.Name.EndsWith("ViewModel")) //.Where(type => type.GetInterface(typeof(INotifyPropertyChanged).Name) != null) .AsSelf().InstancePerDependency(); _logger.Info("ViewModels built"); builder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray()) .Where(type => type.Name.EndsWith("View")) .AsSelf().InstancePerDependency(); _logger.Info("Views built"); builder.Register <IWindowManager>(c => new WindowManager()).InstancePerLifetimeScope(); builder.Register <IEventAggregator>(c => new EventAggregator()).InstancePerLifetimeScope(); _container = builder.Build(); }
private void BuildContainer() { var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(GetType().Assembly) .Where(type => type.Name.EndsWith(Consts.Endings.ViewModel)) .Where(type => type.GetInterface(typeof(INotifyPropertyChanged).Name) != null) .AsSelf() .InstancePerDependency(); builder.RegisterAssemblyTypes(GetType().Assembly) .Where(type => type.Name.EndsWith(Consts.Endings.View)) .AsSelf() .InstancePerDependency(); builder.Register <IWindowManager>(c => new WindowManager()).InstancePerLifetimeScope(); builder.Register <IEventAggregator>(c => new EventAggregator()).SingleInstance(); builder.Register <ICustomDialogManager>(c => new CustomDialogManager()).SingleInstance(); builder.Register <ISerializer>(c => new Serializer()).SingleInstance(); builder.Register <IAlgorithmProvider>(c => new AlgorithmProvider()).SingleInstance(); builder.RegisterType <TaskGenerator>().As <ITaskGenerator>(); _container = builder.Build(); }
public static void InitAutofac() { var builder = new ContainerBuilder(); //注册数据库基础操作和工作单元 builder.RegisterGeneric(typeof(BaseRepository <>)).As(typeof(IRepository <>)).PropertiesAutowired(); builder.RegisterType(typeof(UnitWork)).As(typeof(IUnitWork)).PropertiesAutowired(); //builder.RegisterType(typeof(UserManagerApp)).As(typeof(IUserManagerApp)).InstancePerLifetimeScope(); //注册app层 builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).PropertiesAutowired(); // 注册controller,使用属性注入 builder.RegisterControllers(Assembly.GetCallingAssembly()).PropertiesAutowired(); //注册所有的ApiControllers builder.RegisterApiControllers(Assembly.GetCallingAssembly()).PropertiesAutowired(); builder.RegisterModelBinders(Assembly.GetCallingAssembly()); builder.RegisterModelBinderProvider(); // OPTIONAL: Register web abstractions like HttpContextBase. //builder.RegisterModule<AutofacWebTypesModule>(); // OPTIONAL: Enable property injection in view pages. builder.RegisterSource(new ViewRegistrationSource()); // 注册所有的Attribute builder.RegisterFilterProvider(); // Set the dependency resolver to be Autofac. _container = builder.Build(); //Set the MVC DependencyResolver DependencyResolver.SetResolver(new AutofacDependencyResolver(_container)); //Set the WebApi DependencyResolver GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)_container); }
private void ConfigAutofac(IAppBuilder app) { var builder = new ContainerBuilder(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); // Register your Web API controllers. //builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //Register WebApi Controllers builder.RegisterType <Uow>().As <IUow>().InstancePerRequest(); builder.RegisterType <DbFactory>().As <IDbFactory>().InstancePerRequest(); builder.RegisterType <AptechSem3FinalProjectEntities>().AsSelf().InstancePerRequest(); builder.RegisterAssemblyTypes(typeof(IService <>).Assembly) .Where(t => t.GetTypeInfo() .ImplementedInterfaces.Any( i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IService <>))) .AsImplementedInterfaces().InstancePerRequest(); builder.RegisterAssemblyTypes(typeof(IRepository <>).Assembly) .Where(t => t.GetTypeInfo() .ImplementedInterfaces.Any( i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IRepository <>))) .AsImplementedInterfaces().InstancePerRequest(); // Repositories //builder.RegisterAssemblyTypes(typeof(Repository<User>).Assembly) // .Where(t => t.Name.EndsWith("Repository")) // .AsImplementedInterfaces().InstancePerRequest(); // Services //builder.RegisterGeneric(typeof(IService).Assembly) // .Where(t => t.Name.EndsWith("Service")) // .AsImplementedInterfaces().InstancePerRequest(); Autofac.IContainer container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container); //Set the WebApi DependencyResolver }
public static IServiceProvider InitStartup(string rabbitMq) { var config = new ConfigurationBuilder() .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); //services.Configure<DbOptions>(Configuration.GetSection("sql")); var configuration = config.Build(); var services = new ServiceCollection(); //services.AddOptions<RabbitMqOption>(); //注入IOptions<T>,这样就可以在DI容器中获取IOptions<T>了 //services.Configure<RabbitMqOption>(configuration.GetSection(rabbitMq)); //注入配置数据 //services.Configure<RabbitMqOption>(configuration.GetSection(rabbitMq)); services.AddSingleton <IConfiguration>(configuration); //services.AddSingleton<IUnitOfWork<ASampleSqlServerDbContext>, UnitOfWork<ASampleSqlServerDbContext>>(); services.BuildServiceProvider(); var builder = new ContainerBuilder(); builder.RegisterInstance <IConfiguration>(configuration); ////builder.RegisterInstance<IOptions<RabbitMqOption>>(); //builder.RegisterType<RabbitMqOption>() // .As<IOptions<RabbitMqOption>>() // .InstancePerLifetimeScope(); builder.RegisterAssemblyTypes(Assembly.GetEntryAssembly()) .AsImplementedInterfaces(); //builder.Populate(services); //builder.AddDispatchers(); builder.AddASampleRabbitMq(); Container = builder.Build(); var serviceProvider = new AutofacServiceProvider(Container); return(serviceProvider); }
private static void AutofacRegisters() { Stopwatch watch = new Stopwatch(); watch.Start(); ContainerBuilder builder = new ContainerBuilder(); // builder.RegisterGeneric(typeof(Repository<,>)).As(typeof(IRepository<,>)); Type baseType = typeof(IDependency); string path = Directory.GetCurrentDirectory(); Assembly[] assemblies = Directory.GetFiles(path, "Shoy.*.dll").Select(Assembly.LoadFrom) .Union(new[] { Assembly.GetExecutingAssembly() }).ToArray(); builder.RegisterAssemblyTypes(assemblies) .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract) .AsSelf() //自身服务,用于没有接口的类 .AsImplementedInterfaces() //接口服务 .PropertiesAutowired() //属性注入 .InstancePerLifetimeScope(); //保证生命周期基于请求 Container = builder.Build(); watch.Stop(); Console.WriteLine("register use {0}ms", watch.ElapsedMilliseconds); }
public void Configure(IContainer container) { foreach (var strategy in Strategies) { if (strategy.IndicatorManager == null) strategy.IndicatorManager = container.Resolve<IndicatorManager>(); if (strategy.OrderManager == null) strategy.OrderManager = container.Resolve<OrderManager>(); if (strategy.InstrumentStrategy == null) strategy.InstrumentStrategy = this; foreach (var stopLoss in strategy.StopLosses) { if (stopLoss.IndicatorManager == null) stopLoss.IndicatorManager = container.Resolve<IndicatorManager>(); if (stopLoss.OrderManager == null) stopLoss.OrderManager = container.Resolve<OrderManager>(); if (stopLoss.InstrumentStrategy == null) stopLoss.InstrumentStrategy = this; } foreach (var stopProfit in strategy.StopProfits) { if (stopProfit.IndicatorManager == null) stopProfit.IndicatorManager = container.Resolve<IndicatorManager>(); if (stopProfit.OrderManager == null) stopProfit.OrderManager = container.Resolve<OrderManager>(); if (stopProfit.InstrumentStrategy == null) stopProfit.InstrumentStrategy = this; } } }
private static void Main() { AppDomain.CurrentDomain.UnhandledException += OnException; var cb = new ContainerBuilder(); cb.RegisterModule<BaseEditorsAutofacModule>(); cb.RegisterModule<MarmaladeEditorsAutofacModule>(); cb.RegisterModule<GenericSceneEditorsAutofacModule>(); cb.RegisterModule<AseAutofacModule>(); cb.RegisterModule<DaeAutofacModule>(); cb.RegisterModule<BspAutofacModule>(); cb.RegisterModule<SvgAutofacModule>(); cb.RegisterModule<MarmaladeAutofacModule>(); cb.RegisterModule<MarmaladeTextFilesAutofacModule>(); cb.RegisterModule<MarmaladeBinaryFilesAutofacModule>(); cb.RegisterModule<MarmaladeTextureFilesAutofacModule>(); cb.RegisterGeneric(typeof(BindingList<>)).UsingConstructor(new Type[] { }).As(typeof(IList<>)); //cb.RegisterGeneric(typeof(EditorConfiguration<>)).As(typeof(IEditorOptions<>)).SingleInstance(); cb.RegisterType<EditorEnvironment>().As<IEditorEnvironment>().SingleInstance(); cb.RegisterType<ResourceManager>().As<IResourceManager>().SingleInstance(); cb.RegisterType<ResourceFile>().As<IResourceFile>().InstancePerDependency(); cb.RegisterType<ResourceFileItem>().As<IResourceFileItem>().InstancePerDependency(); cb.RegisterType<EditorResourceErrorHandler>().As<IResourceErrorHandler>().SingleInstance(); cb.RegisterType<ToeGraphicsContext>().As<ToeGraphicsContext>().SingleInstance(); cb.RegisterInstance(OpenTkStreamConverterFactory.Default).As<IStreamConverterFactory>().SingleInstance(); cb.RegisterType<AddNewItemForm>().InstancePerDependency(); cb.RegisterType<MainEditorWindow>().SingleInstance(); using (container = cb.Build()) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(container.Resolve<MainEditorWindow>()); } }
public AutofacUseCase() { var builder = new Autofac.ContainerBuilder(); builder.RegisterType<WebApp>() .As<IWebApp>(); builder.RegisterType<Authenticator>() .As<IAuthenticator>(); builder.RegisterType<StockQuote>() .As<IStockQuote>(); builder.RegisterType<Logger>() .As<ILogger>(); builder.RegisterType<ErrorHandler>() .As<IErrorHandler>(); builder.RegisterType<Database>() .As<IDatabase>(); this._container = builder.Build(); }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initilaization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this)); base.Initialize(); var cb = new ContainerBuilder(); cb.RegisterModule<BaseEditorsAutofacModule>(); cb.RegisterModule<MarmaladeEditorsAutofacModule>(); cb.RegisterModule<GenericSceneEditorsAutofacModule>(); cb.RegisterModule<MarmaladeAutofacModule>(); cb.RegisterModule<AseAutofacModule>(); cb.RegisterModule<DaeAutofacModule>(); cb.RegisterModule<BspAutofacModule>(); cb.RegisterModule<MarmaladeTextFilesAutofacModule>(); cb.RegisterModule<MarmaladeBinaryFilesAutofacModule>(); cb.RegisterModule<MarmaladeTextureFilesAutofacModule>(); cb.RegisterGeneric(typeof(BindingList<>)).UsingConstructor(new Type[] { }).As(typeof(IList<>)); cb.RegisterType<VsEditorEnvironment>().As<IEditorEnvironment>().SingleInstance(); cb.RegisterType<ResourceManager>().As<IResourceManager>().SingleInstance(); cb.RegisterType<ResourceFile>().As<IResourceFile>().InstancePerDependency(); cb.RegisterType<ResourceFileItem>().As<IResourceFileItem>().InstancePerDependency(); cb.RegisterType<ResourceEditorFactory>().As<IResourceEditorFactory>().SingleInstance(); cb.RegisterType<EditorResourceErrorHandler>().As<IResourceErrorHandler>().SingleInstance(); cb.RegisterType<ToeGraphicsContext>().As<ToeGraphicsContext>().SingleInstance(); cb.RegisterType<EditorFactory>().As<IVsEditorFactory>().SingleInstance(); cb.RegisterInstance(this).As<Package>().As<ToeVisualStudioExtensionPackage>().ExternallyOwned(); container = cb.Build(); foreach (var f in container.Resolve<IEnumerable<IVsEditorFactory>>()) { //Create Editor Factory. Note that the base Package class will call Dispose on it. base.RegisterEditorFactory(f); } }
protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { if (container != null) { container.Dispose(); container = null; } } }
private void PopulateDIContainer() { var builder = new ContainerBuilder(); //builder.Register<UserSettingsRepository>(new UserSettingsRepository()); builder.Register(new WordListCatalog()).SingletonScoped(); builder.Register<IProgressNotificationProvider>(new DialogProgressNotificationProvider()); builder.Register<LexEntryRepository>( c => c.Resolve<IProgressNotificationProvider>().Go<LexEntryRepository>("Loading Dictionary", progressState => new LexEntryRepository(_pathToLiftFile, progressState))); //builder.Register<ViewTemplate>(DefaultPrintingTemplate).Named("PrintingTemplate"); var catalog = new TaskTypeCatalog(); catalog.RegisterAllTypes(builder); builder.Register<TaskTypeCatalog>(catalog).SingletonScoped(); //this is a bit weird, did it to get around a strange problem where it was left open, //never found out by whom. But note, it does affect behavior. It means that //the first time the reader is asked for, it will be reading the value as it was //back when we did this assignment. string configFileText = File.ReadAllText(PathToConfigFile); builder.Register<ConfigFileReader>(c => new ConfigFileReader(configFileText, catalog)).SingletonScoped(); builder.Register<TaskCollection>().SingletonScoped(); foreach (var viewTemplate in ConfigFileReader.CreateViewTemplates(configFileText)) { //todo: this isn't going to work if we start using multiple tempates. //will have to go to a naming system. builder.Register(viewTemplate).SingletonScoped(); } // builder.Register<ViewTemplate>(DefaultViewTemplate); // builder.Register(DefaultViewTemplate); // can't currently get at the instance //someday: builder.Register<StringCatalog>(new StringCatalog()).ExternallyOwned(); _container = builder.Build(); }
public WinFormsFactory(ChorusSystem parent, IContainer container) { _parent = parent; _container = container; }
private void FinishInit(string userNameForHistoryAndNotes, ContainerBuilder builder) { _user = new ChorusUser(userNameForHistoryAndNotes); builder.RegisterInstance(_user).As<IChorusUser>(); // builder.RegisterGeneratedFactory<NotesInProjectView.Factory>().ContainerScoped(); // builder.RegisterGeneratedFactory<NotesInProjectViewModel.Factory>().ContainerScoped(); // builder.RegisterGeneratedFactory<NotesBrowserPage.Factory>().ContainerScoped(); // builder.Register(new NullProgress());//TODO _container = builder.Build(); //add the container itself var builder2 = new Autofac.ContainerBuilder(); builder2.RegisterInstance(_container).As<IContainer>(); builder2.Update(_container); DidLoadUpCorrectly = true; }
static void BuildContainer() { _fileService = new Drey.Server.Services.FilesytemFileService(PACKAGES_DIR); ContainerBuilder cb = new ContainerBuilder(); cb.RegisterInstance(_fileService); cb.RegisterType<Drey.Server.EventBus>().AsImplementedInterfaces().SingleInstance(); cb.RegisterType<Stores.ReleasesStore>().AsImplementedInterfaces(); cb.RegisterType<Drey.Server.Services.PackageService>().AsImplementedInterfaces(); cb.RegisterType<Services.ClientHealthService>().AsImplementedInterfaces(); cb.RegisterType<Services.GroupMembershipService>().AsImplementedInterfaces(); cb.RegisterType<Infrastructure.SampleClientRegistry>().AsImplementedInterfaces().SingleInstance(); cb.RegisterType<Drey.Server.Services.AnonymousNugetApiClaimsValidator>().AsImplementedInterfaces(); var serverASM = Assembly.LoadFrom(Path.Combine(Environment.CurrentDirectory, "Drey.Server.Hubs.dll")); cb.RegisterAssemblyTypes(serverASM) .Where(t => t.Name.EndsWith("Director")) .AsImplementedInterfaces(); cb.RegisterHubs(serverASM); _container = cb.Build(); }
/// <summary> /// Do not override this method. This is where the IoC container is configured. /// </summary> /// <exception cref="NullReferenceException"> /// Either CreateFrameAdapter or CreateWindowManager or CreateEventAggregator or /// CreatePhoneApplicationServiceAdapter or CreateVibrateController or /// CreateSoundEffectPlayer is null. /// </exception> protected override void Configure() { // allow base classes to change bootstrapper settings ConfigureBootstrapper(); // validate settings if (CreateFrameAdapter == null) { throw new NullReferenceException("CreateFrameAdapter is not specified."); } if (CreateWindowManager == null) { throw new NullReferenceException("CreateWindowManager is not specified."); } if (CreateEventAggregator == null) { throw new NullReferenceException("CreateEventAggregator is not specified."); } if (CreatePhoneApplicationServiceAdapter == null) { throw new NullReferenceException( "CreatePhoneApplicationServiceAdapter is not specified."); } if (CreateVibrateController == null) { throw new NullReferenceException("CreateVibrateController is not specified."); } if (CreateSoundEffectPlayer == null) { throw new NullReferenceException("CreateSoundEffectPlayer is not specified."); } // Configure container. ContainerBuilder lBuilder = new ContainerBuilder(); // Register phone services. Assembly lCaliburnAssembly = typeof (IStorageMechanism).Assembly; // Register IStorageMechanism implementors. lBuilder.RegisterAssemblyTypes(lCaliburnAssembly) .Where( aType => typeof (IStorageMechanism).IsAssignableFrom(aType) && !aType.IsAbstract && !aType.IsInterface) .As<IStorageMechanism>() .InstancePerLifetimeScope(); // Register IStorageHandler implementors. lBuilder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray()) .Where( aType => typeof (IStorageHandler).IsAssignableFrom(aType) && !aType.IsAbstract && !aType.IsInterface) .As<IStorageHandler>() .InstancePerLifetimeScope(); // Register view models. lBuilder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray()) // Must be a type with a name that ends with ViewModel. .Where(aType => aType.Name.EndsWith("ViewModel")) // Mmust be in a namespace ending with ViewModels. .Where( aType => !EnforceNamespaceConvention || (!string.IsNullOrEmpty(aType.Namespace) && aType.Namespace.EndsWith("ViewModels"))) // Must implement INotifyPropertyChanged (deriving from PropertyChangedBase will statisfy this). .Where(aType => aType.GetInterface(ViewModelBaseType.Name, false) != null) // Registered as self. .AsSelf() // Subscribe on Activated event for viewmodels to make storage mechanism work. .OnActivated(aArgs => ActivateInstance(aArgs.Instance)) // Always create a new one. .InstancePerDependency(); // Register views. lBuilder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray()) // Must be a type with a name that ends with View. .Where(aType => aType.Name.EndsWith("View")) // Must be in a namespace that ends in Views. .Where( aType => !EnforceNamespaceConvention || (!string.IsNullOrEmpty(aType.Namespace) && aType.Namespace.EndsWith("Views"))) // Registered as self. .AsSelf() // Always create a new one. .InstancePerDependency(); // Register the singletons. lBuilder.Register<IPhoneContainer>( aContext => new AutofacPhoneContainer(aContext.Resolve<IComponentContext>())) .SingleInstance(); lBuilder.RegisterInstance<INavigationService>(CreateFrameAdapter()) .SingleInstance(); PhoneApplicationServiceAdapter lPhoneService = CreatePhoneApplicationServiceAdapter(); lBuilder.RegisterInstance<IPhoneService>(lPhoneService) .SingleInstance(); lBuilder.Register(aContext => CreateEventAggregator()) .SingleInstance(); lBuilder.Register(aContext => CreateWindowManager()) .SingleInstance(); lBuilder.Register(aContext => CreateVibrateController()) .SingleInstance(); lBuilder.Register(aContext => CreateSoundEffectPlayer()) .SingleInstance(); lBuilder.RegisterType<StorageCoordinator>().AsSelf() .SingleInstance(); lBuilder.RegisterType<TaskController>().AsSelf() .SingleInstance(); // Allow derived classes to add to the container. ConfigureContainer(lBuilder); // Build the container Container = lBuilder.Build(); // Get the phone container instance. PhoneContainer = (AutofacPhoneContainer) Container.Resolve<IPhoneContainer>(); // Start the storage coordinator. StorageCoordinator lStorageCoordinator = Container.Resolve<StorageCoordinator>(); lStorageCoordinator.Start(); // Start the task controller. TaskController lTaskController = Container.Resolve<TaskController>(); lTaskController.Start(); // Add custom conventions for the phone. AddCustomConventions(); }
static ValidationResult Setup(SplashScreen splashScreen) { var validator = new SPFInstalledValidator(); if (validator.RunValidator() == ValidationResult.Error) { MessageBox.Show(validator.ErrorString+Environment.NewLine+Environment.NewLine+validator.QuestionString, SPMEnvironment.Version.Title + " Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return ValidationResult.Error; } var builder = new ContainerBuilder(); // Find all the assemblies for this application builder.RegisterModule(new AutoLoadAssemblies()); // Build the container now! autoFacContainer = builder.Build(); //CompositionProvider.LoadAssemblies(); IoCContainer = autoFacContainer.Resolve<IContainerAdapter>(); var provider = IoCContainer.Resolve<SettingsProvider>(); provider.Load(); var engine = new PreflightController(splashScreen, IoCContainer); if (!engine.Validate()) { return ValidationResult.Error; } Window = IoCContainer.Resolve<MainWindow>(); Window.SplashScreenLoad(splashScreen); return ValidationResult.Success; }
public void TearDown() { this.Container.Dispose(); this.container = null; }